C#与Java互通AES算法加密解密

利用AES加密算法对报文进行加密解密,实现C#与Java互通,网上查了一堆也许是因为版本的原因都用不了,于是还是静心下来自己写个:

 

直接上代码:

C# 需要引用System.Security.Cryptography命名空间

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// <summary>AES加密</summary>
/// <param name="text">明文</param>
/// <param name="key">密钥,长度为16的字符串</param>
/// <param name="iv">偏移量,长度为16的字符串</param>
/// <returns>密文</returns>
public static string EncodeAES(string text, string key,string iv)
{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.Zeros;
    rijndaelCipher.KeySize = 128;
    rijndaelCipher.BlockSize = 128;
    byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[16];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length)
        len = keyBytes.Length;
    System.Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
    ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
    byte[] plainText = Encoding.UTF8.GetBytes(text);
    byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
    return Convert.ToBase64String(cipherBytes);
}
 
/// <summary>AES解密</summary>
/// <param name="text">密文</param>
/// <param name="key">密钥,长度为16的字符串</param>
/// <param name="iv">偏移量,长度为16的字符串</param>
/// <returns>明文</returns>
public static string DecodeAES(string text, string key,string iv)
{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.CBC;
    rijndaelCipher.Padding = PaddingMode.Zeros;
    rijndaelCipher.KeySize = 128;
    rijndaelCipher.BlockSize = 128;
    byte[] encryptedData = Convert.FromBase64String(text);
    byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[16];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length)
        len = keyBytes.Length;
    System.Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    rijndaelCipher.IV = Encoding.UTF8.GetBytes(iv);
    ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
    byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    return Encoding.UTF8.GetString(plainText);
}

  

Java,需要以下引用:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

另外需要对String和byte[]相互转换的类,我自己写的Base64Helper

 

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * @author miracle.qu
 * @see AES算法加密明文
 * @param data 明文
 * @param key 密钥,长度16
 * @param iv 偏移量,长度16
 * @return 密文
 */
  public static String encryptAES(String data,String key,String iv) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
             
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
 
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
              
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
 
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
 
            return Base64Helper.encode(encrypted).trim();
 
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * @author miracle.qu
     * @see AES算法解密密文
     * @param data 密文
     * @param key 密钥,长度16
     * @param iv 偏移量,长度16
     * @return 明文
     */
    public static String decryptAES(String data,String key,String iv) throws Exception {
        try
        {
            byte[] encrypted1 = Base64Helper.decode(data);
              
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
              
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
 
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString.trim();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

  其中Base64Helper类是个简单的类,引用:

 

import org.apache.commons.codec.binary.Base64;

 

其中核心代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * 编码
 * @param byteArray
 * @return
 */
public static String encode(byte[] byteArray) {
    return new String(new Base64().encode(byteArray));
}
 
/**
 * 解码
 * @param base64EncodedString
 * @return
 */
public static byte[] decode(String base64EncodedString) {
    return new Base64().decode(base64EncodedString);
}

  

原文地址:  https://blog.csdn.net/mr_qu/article/details/8433370

 

posted on   大西瓜3721  阅读(804)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2016-03-01 C#百万数据查询超时问题
2016-03-01 浅谈web网站架构演变过程

导航

点击右上角即可分享
微信分享提示