c# AES 解密 快手店铺 java的AES加密方法
JAVA版本的解密:
/** * 参数说明: * message:带解密的密文 * privateKey: 加密密钥 **/ String decodeMessage = PlatformEventSecurityUtil.decode(message, privateKey); /** * 方法详情 **/ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String KEY_ALGORITHM = "AES"; private static final String CHARSET = "UTF-8"; public static String decode(String message, String privateKey) throws KsMerchantApiException { try { if (KsStringUtils.isBlank(message) || KsStringUtils.isBlank(privateKey)) { throw new KsMerchantApiException("decode param is blank"); } Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); byte[] key = Base64.decodeBase64(privateKey); SecretKeySpec keySpec = new SecretKeySpec(key, KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(new byte[16])); return new String(cipher.doFinal(Base64.decodeBase64(message)), CHARSET); } catch (Exception e) { throw new KsMerchantApiException("decode message fail", e); } }
c#(.NET 6)解密
注意:JAVA初始向量是一个 new byte[16]全0的byte内容。所以C#也一样有这个向量参数,快手官方文档没有说明这点。
public string DecodeAES(string text, string key) { using Aes rijndaelCipher = Aes.Create(); rijndaelCipher.Mode = CipherMode.CBC; rijndaelCipher.Padding = PaddingMode.None; rijndaelCipher.BlockSize = 128; byte[] pwdBytes = Convert.FromBase64String(key); byte[] ivBytes = new byte[16]; //初始向量是一个 new byte[16]全0的byte内容 。C#语言的解密执行逻辑可能需要和 java-sdk保持一致 for (int i = 0; i < ivBytes.Length; i++) { ivBytes[i] = (byte)0; } byte[] encryptedData = Convert.FromBase64String(text); rijndaelCipher.Key = pwdBytes; rijndaelCipher.IV = ivBytes; ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(plainText); }