1、首先排除数据库中读取加密后的字段是否被强制截断。
2、AES加密后的byte[]首先应用base64( Convert.ToBase64String)编码一次,若直接用utf8的话会报上述错误,若用unicode编码的话会解密成乱码,原因是加密后的byte数组用其他编码方式编码的话会丢失字符。
3、base编码后的字符串恢复为数组可用Convert.FromBase64String。
加密:
public static byte[] AESEncrypt(string plainText) { SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText); des.Key = Encoding.UTF8.GetBytes(keys); des.IV = _key1;
ICryptoTransform cTransform = des.CreateEncryptor(); return cTransform.TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); }
解密:
public static byte[] AESDecrypt(byte[] cipherText) { SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.UTF8.GetBytes(keys); des.IV = _key1; ICryptoTransform cTransform = des.CreateDecryptor(); return cTransform.TransformFinalBlock(cipherText, 0, cipherText.Length); }
public static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; public static string keys = "dongbinhuiasxiny";//密钥,128位