以C#的 AEC加密解密为例
加密:
private static string EncryptBase(string text, string password, string iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
//rijndaelCipher.Padding = PaddingMode.Zeros; //0补位
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
解密:
private static string DecryptBase(string text, string password, string iv)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
//rijndaelCipher.Padding = PaddingMode.Zeros;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(HttpUtility.UrlDecode(text));
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
解说上面代码:
1:加密解密 使用模式:rijndaelCipher.Mode=CBC
2:使用填充模式:rijndaelCipher.Padding无控制即为默认值PKCS5
3:密钥长度:rijndaelCipher.KeySize=128;rijndaelCipher.BlockSize=128
4:加密密钥最终为base64编码
如果使用上述代码解密Java类型的加密值,我们应该注意点什么(反之亦然)
注意点:
1:运算模式:【CBC】,【ECB】,【OFB】,【CFB】,【CTS】
2:填充模式:【None】,【PKCS7】,【Zeros】,【ANSIX923】,【ISO10126】
1) C# 默认 AES加密 为 【None】=PKCS5
2)Java一般默认使用PKCS7
3:是否存在加密密钥和加密矢量IV
4:密钥的长度可以使用128位、192位或256位。密钥长不同加密齿轮不同。
ps:如果我们把以上注意点记清楚了,不管是与Java还是PHP亦或者其他 加密也好解密也罢 都是很好对接的
额外补充点:
关于加密模式一般使用AES,DES,RAS,MD5这四种模式
1:AES:对称加密,较DES安全快速。适合大数据明文加密
2:DES:对称加密,密钥不安全。适合大数据明文加密
3:RSA:非对称加密。安全,适合小数据量加密。一般使用DES+RSA组合形式进行加密
4:MD5:不可逆加密方式。
来源:CSDN
作者:坏蛋栀子花
链接:https://blog.csdn.net/u011791378/article/details/103573965