首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java实现Aes加密,用C#解密

用Java实现Aes加密,用C#解密
EN

Stack Overflow用户
提问于 2020-06-28 16:35:50
回答 1查看 85关注 0票数 0

在Java代码中,我有源代码可以很好地工作,这是用于加密:

代码语言:javascript
复制
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Arrays;
    import java.util.Base64;
    import javax.crypto.spec.IvParameterSpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    
    public class HelloWorld{
        private static final String hexKey = "B8EE12E123C0E300A202074A153CC0D27D739357480FFFFFFFFFFFFFFFFFFFEF";
        
         public static void main(String []args){
            System.out.println("Encryt ==== ");
            String textToEncrypt = "From=ABC&Key=FootID1234&Value=ResultValue2324";
            String encryptedText = encrypt(textToEncrypt);
            System.out.println(encryptedText);
            System.out.println("Decrypt ==== ");
            String decryptedText = decrypt(encryptedText);
            System.out.println(decryptedText);
         }
         
         public static String encrypt (String plainText) {
            String encryptedText = null;
            try {
                
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                SecretKeySpec secretKey = new SecretKeySpec(hexToBytes(hexKey), "AES");
                            
                IvParameterSpec ivparameterspec = new IvParameterSpec(hexKey.getBytes(), 0, 16);
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivparameterspec);
                byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF8"));
                
                encryptedText = bytesToHex(cipherText);
            } catch (Exception E) {
                System.out.println("Encrypt Exception : " + E.getMessage());
            }
            return encryptedText;
        }
       
        public static String decrypt(String encryptedText) {
            String decryptedText = null;
            try {
                
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
                SecretKeySpec secretKey = new SecretKeySpec(hexToBytes(hexKey), "AES");
                
                IvParameterSpec ivparameterspec = new IvParameterSpec(hexKey.getBytes("UTF8"), 0, 16);
                cipher.init(Cipher.DECRYPT_MODE, secretKey, ivparameterspec);
                byte[] cipherText = hexToBytes(encryptedText);
                byte[] dcrbyte = cipher.doFinal(cipherText);
                decryptedText = new String(dcrbyte, "UTF-8");
    
            } catch (Exception E) {
                 System.out.println("Encrypt Exception : " + E.getMessage());
            }
            return decryptedText;
        }
        
        private static byte[] hexToBytes(String hexStr) {
            byte[] val = new byte[hexStr.length() / 2];
            for (int i = 0; i < val.length; i++) {
                int idx = i * 2;
                int j = Integer.parseInt(hexStr.substring(idx, idx + 2), 16);
                val[i] = (byte) j;
            }
            return val;
        }
    
        private static String bytesToHex(byte[] hashInBytes) {
                char[] hexArray = "0123456789ABCDEF".toCharArray();
                char[] hexChars = new char[hashInBytes.length * 2];
                for (int i = 0; i < hashInBytes.length; i++) {
                    int v = hashInBytes[i] & 0xFF;
                    hexChars[i * 2] = hexArray[v >>> 4];
                    hexChars[i * 2 + 1] = hexArray[v & 0x0F];
                }
                return new String(hexChars);
            }
    }

在c#中,我尝试这样编写decryptAes()函数:

代码语言:javascript
复制
public static class Encryption
    {
        // use these parameters to test decryptAes()
        //string key = "B8EE12E123C0E300A202074A153CC0D27D739357480FFFFFFFFFFFFFFFFFFFEF";
        //string textToDecrypt = "756AD4D80E2CF1E289D55A23E092F012E8D5F372A343A419BC87F77B6335F04EFB41C3B56F5CDA167F90F67CD672A186";

        public static string decryptAes(string key, string textToDecrypt)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            // Assumed Mode and padding values.
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            // AssumedKeySize and BlockSize values.
            rijndaelCipher.KeySize = 0x80; //128
            rijndaelCipher.BlockSize = 0x80;

            // Convert Hex keys to byte Array.
            byte[] encryptedData = HexToBytes(textToDecrypt);
            //byte[] pwdBytes = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(key);
            byte[] pwdBytes = HexToBytes(key);

            byte[] keyBytes = new byte[0x10]; //16
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
            {
                len = keyBytes.Length;
            }
            Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = keyBytes;

            // Decrypt data
            byte[] plainText = rijndaelCipher.CreateDecryptor()
                .TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);
        }

        public static byte[] HexToBytes(string str)
        {
            if (str.Length == 0 || str.Length % 2 != 0)
                return new byte[0];
            byte[] buffer = new byte[str.Length / 2];
            char c;
            for (int bx = 0, sx = 0; bx < buffer.Length; ++bx, ++sx)
            {
                // Convert first half of byte
                c = str[sx];
                buffer[bx] = (byte)((c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0')) << 4);
                // Convert second half of byte
                c = str[++sx];
                buffer[bx] |= (byte)(c > '9' ? (c > 'Z' ? (c - 'a' + 10) : (c - 'A' + 10)) : (c - '0'));
            }
            return buffer;
        }

        public static string ByteToHex(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString().ToUpper();
        }
    }

但是c# decryptAes()函数并没有像我期望的那样工作。一个错误

代码语言:javascript
复制
System.Security.Cryptography.CryptographicException: 'Padding is invalid and cannot be removed.'

发生在第rijndaelCipher.Padding = PaddingMode.PKCS7;

当我更改为rijndaelCipher.Padding = PaddingMode.None时,它不能像我预期的那样工作,c#结果与java的结果不同。

请帮助,任何建议都将不胜感激!谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-06-28 16:43:23

您需要显式设置加密和解密的填充。除非您有其他理由,否则请使用PKCS#7填充。

rijndaelCipher.Padding=PaddingMode.none;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62620145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档