C#对接JAVA系统遇到的AES加密坑

起因对接合作伙伴的系统,需要对数据进行AES加密

默认的使用了已经写好的帮助类中加密算法,发现结果不对,各种尝试改变加密模式改变向量等等折腾快一下午。最后网上查了下AES在JAVA里面的实现完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public  static  String AesEncrypt(String content,String encyKey) {           
         try  {                  
             KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
             SecureRandom secureRandom = SecureRandom.getInstance( "SHA1PRNG" );  
             secureRandom.setSeed(encyKey.getBytes());  
             kgen.init( 128 , secureRandom);
             Cipher cipher=Cipher.getInstance( "AES" );       
             cipher.init(Cipher.DECRYPT_MODE, new  SecretKeySpec(kgen.generateKey().getEncoded(), "AES" ));         
             byte [] byteContent = content.getBytes( "utf-8" );
             byte [] result = cipher.doFinal(byteContent);           
             BASE64Encoder  encode =  new  BASE64Encoder ();
             String strResult=encode.encode(result);
             return  strResult;
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  null ;
   }

 根据博主:http://www.cnblogs.com/amylis_chen/p/6107162.html#commentform  的经验有了思路

解决办法,通过JAVA代码生成AES的密钥,再通过C#代码进行AES加密

1
2
3
4
5
6
7
8
9
10
//JAVA代码生成密钥
         String encyKey= "合作伙伴提供的密钥 " ;
         KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
         java.security.SecureRandom random = java.security.SecureRandom.getInstance( "SHA1PRNG" );
         random.setSeed(encyKey.getBytes());
         kgen.init( 128 , random); 
         SecretKey secretKey = kgen.generateKey();
         byte [] enCodeFormat = secretKey.getEncoded();
         BASE64Encoder coder =  new  BASE64Encoder();       
         System.out.println(coder.encode(enCodeFormat));

 

C#代码进行AES加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class  Program
    {
        static  void  Main( string [] args)
        {
            //默认密钥向量
            var  result = AESEncode( "123456" "JAVA代码输出的密钥" );
            Console.WriteLine(result);
            Console.ReadLine();
 
        }
        public  static  string  AESEncode( string  encryptString,  string  encryptKey)
        {
            if  ( string .IsNullOrEmpty(encryptString))  return  null ;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString);
            RijndaelManaged rm =  new  RijndaelManaged
            {
                Key = Convert.FromBase64String(encryptKey),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return  Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
    }

转载于:https://www.cnblogs.com/tsql/p/9435711.html

你可能感兴趣的:(C#对接JAVA系统遇到的AES加密坑)