实际测试 KEY 是 16个 byte,byte[] byteKEY = System.Convert.FromBase64String(key); 注意:是Convert.FromBase64String转 byte[] , 而不是 Encoding.UTF8.GetBytes 转 byte[] 。
IV 也是 16个 byte,全是0;
--
/// <summary> /// 支付宝小程序AES密钥解密 /// </summary> /// <param name="decryptStr"></param> /// <param name="key">小程序后台设置里的AES密钥</param> /// <returns></returns> public static string AliPayLittleAppAesDecrypt(string decryptStr, string key) { //IV 16 个 byte 都是 0 int ivSize = 16; byte[] iv = new byte[ivSize]; for (int i = 0; i < ivSize; ++i) { iv[i] = 0; } //https://docs.open.alipay.com/common/104567 //支付宝小程序的AES密钥串是BASE64编码过的,所以这里的BYTE KEY 是 System.Convert.FromBase64String //转换后,16 个 byte,是AES128。 byte[] byteKEY = System.Convert.FromBase64String(key); byte[] byteDecrypt = System.Convert.FromBase64String(decryptStr); var _aes = new RijndaelManaged(); _aes.Padding = PaddingMode.PKCS7; _aes.Mode = CipherMode.CBC; //重新指定下KEY和IV,让 RijndaelManaged自动计算KEYSIZE; _aes.Key = byteKEY; _aes.IV = iv; var _crypto = _aes.CreateDecryptor(byteKEY, iv); byte[] decrypted = _crypto.TransformFinalBlock( byteDecrypt, 0, byteDecrypt.Length); _crypto.Dispose(); return Encoding.UTF8.GetString(decrypted); }
--