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);
 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章