Python与C#的AES加密解密对接
python版本的加解密
from Crypto.Cipher import AES import base64 import hashlib def jm_sha256(data): sha256 = hashlib.sha256() sha256.update(data.encode("utf-8")) res = sha256.digest() # print("sha256加密结果:", res) return res def pkcs7padding(text): bs = AES.block_size length = len(text) bytes_length = len(bytes(text, encoding='utf-8')) # tips:utf-8编码时,英文占1个byte,而中文占3个byte padding_size = length if(bytes_length == length) else bytes_length padding = bs - padding_size % bs # tips:chr(padding)看与其它语言的约定,有的会使用'\0' padding_text = chr(padding) * padding return text + padding_text def aes_encrypt_v2(content, key): key_bytes = jm_sha256(key) iv = "\0".encode("utf-8") * 16 aes = AES.new(key_bytes, AES.MODE_CBC, iv) content_padding = pkcs7padding(content) encrypt_bytes = aes.encrypt(bytes(content_padding, encoding='utf-8')) result = str(base64.b64encode(encrypt_bytes), encoding='utf-8') return result mystr1 = "123" mykey1 = "12345678" # 3gVLeGnili1JBTYLHAk8pQ== print(aes_encrypt_v2(mystr1, mykey1)) mystr2 = "你好abcd1234" mykey2 = "1234567812345678" # Qkz+MXCIESJZVgHJffouTQ== print(aes_encrypt_v2(mystr2, mykey2))
对应的C#版本的加解密
/// <summary> /// AES加密 /// </summary> /// <param name="toEncrypt"></param> /// <param name="key"></param> /// <returns></returns> public static string AesPythonEncrypt(string toEncrypt, string key) { var keyArray = SHAPython256(key); var toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt); byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; var rDel = new RijndaelManaged { Key = keyArray, IV = iv, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, BlockSize = 128 }; var cTransform = rDel.CreateEncryptor(); var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static byte[] SHAPython256(string str) { var SHA256Data = Encoding.UTF8.GetBytes(str); var Sha256 = new SHA256Managed(); var by = Sha256.ComputeHash(SHA256Data); return by; } /// <summary> /// AES解密 /// </summary> /// <param name="decryptStr">密文</param> /// <param name="key">密钥</param> /// <returns></returns> public string Decrypt(string decryptStr, string key) { var _aes = new AesCryptoServiceProvider(); _aes.BlockSize = 128; _aes.KeySize = 256; byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; var keyArray = SHAPython256(key); _aes.Key = keyArray; _aes.IV = iv;//Encoding.UTF8.GetBytes(IV); _aes.Padding = PaddingMode.PKCS7; _aes.Mode = CipherMode.CBC; var _crypto = _aes.CreateDecryptor(_aes.Key, _aes.IV); byte[] decrypted = _crypto.TransformFinalBlock( System.Convert.FromBase64String(decryptStr), 0, System.Convert.FromBase64String(decryptStr).Length); _crypto.Dispose(); return Encoding.UTF8.GetString(decrypted); }
就这么简单。