问题描述
下面这段是用C#做的AES加密,请教各位大神如何用java实现,谢谢!usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Text;usingSystem.Security.Cryptography;namespaceAES加密解密{///<summary>///AES加密解密类///</summary>publicclassAES{///<summary>///AES加密算法,返回加密结果///</summary>///<paramname="toEncrypt">加密字符串</param>///<paramname="sKey">密钥</param>///<returnsvalue="string">加密结果</returns>publicstaticstringAESEncrypt(stringtoEncrypt,stringsKey){sKey+="qDj46SdehW";if(string.IsNullOrEmpty(toEncrypt)||string.IsNullOrEmpty(sKey))return"";byte[]toEncryptArray=UTF8Encoding.UTF8.GetBytes(toEncrypt);RijndaelManagedrDel=newRijndaelManaged();rDel.Key=GetLegalKey(sKey);//Console.Write(rDel.Key);rDel.IV=GetLegalIV(sKey);//Console.Write(rDel.Key);rDel.Mode=CipherMode.ECB;rDel.Padding=PaddingMode.PKCS7;ICryptoTransformcTransform=rDel.CreateEncryptor();byte[]resultArray=cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);cTransform.Dispose();returnConvert.ToBase64String(resultArray,0,resultArray.Length);}///<summary>///AES解密算法,返回解密结果///</summary>///<paramname="toDecrypt">解密字符串</param>///<paramname="sKey">密钥</param>///<returnsvalue="string">解密结果</returns>publicstaticstringAESDecrypt(stringtoDecrypt,stringsKey){sKey+="qDj46SdehW";if(string.IsNullOrEmpty(toDecrypt)||string.IsNullOrEmpty(sKey))return"";stringtoD="";intlen=toDecrypt.Length;if(len%4==0)toD=toDecrypt;elsetoD=toDecrypt.PadRight((len+4-len%4),'+');try{byte[]toEncryptArray=Convert.FromBase64String(toD);RijndaelManagedrDel=newRijndaelManaged();rDel.Key=GetLegalKey(sKey);rDel.IV=GetLegalIV(sKey);rDel.Mode=CipherMode.ECB;rDel.Padding=PaddingMode.PKCS7;ICryptoTransformcTransform=rDel.CreateDecryptor();byte[]resultArray=cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);cTransform.Dispose();returnUTF8Encoding.UTF8.GetString(resultArray);}catch{return"";}}///<summary>///获得密钥///</summary>///<paramname="Key">密钥值</param>///<returns></returns>privatestaticbyte[]GetLegalKey(stringKey){SymmetricAlgorithmmobjCryptoService=newRijndaelManaged();stringsTemp=Key;mobjCryptoService.GenerateKey();byte[]bytTemp=mobjCryptoService.Key;intKeyLength=bytTemp.Length;if(sTemp.Length>KeyLength)sTemp=sTemp.Substring(0,KeyLength);elseif(sTemp.Length<KeyLength)sTemp=sTemp.PadRight(KeyLength,'');Console.Write("密钥:"+sTemp);returnASCIIEncoding.ASCII.GetBytes(sTemp);}///<summary>///获取算法的初始化向量///</summary>///<paramname="IV"></param>///<returns></returns>privatestaticbyte[]GetLegalIV(stringIV){SymmetricAlgorithmmobjCryptoService=newRijndaelManaged();stringsTemp=IV;mobjCryptoService.GenerateIV();byte[]bytTemp=mobjCryptoService.IV;intIVLength=bytTemp.Length;if(sTemp.Length>IVLength)sTemp=sTemp.Substring(0,IVLength);elseif(sTemp.Length<IVLength)sTemp=sTemp.PadRight(IVLength,'');Console.Write("向量:"+sTemp);returnUTF8Encoding.UTF8.GetBytes(sTemp);}staticvoidMain(){Stringstr=AESEncrypt("85493409","W32*F4U6R4C");Console.Write("加密结果:"+str);}}}
解决方案
本帖最后由 zyfwj 于 2015-10-28 14:03:45 编辑