JAVA和C#通用的AES加密

JAVA版本

AESUtils工具类
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AESUtils {

    //实际的加密解密操作
    private static byte[] Operation(byte[] src,String key,int mode) throws Exception{
        if (key==null) {
            System.out.println("Key不能为空");
            return null;
        }
        if (key.length()!=16) {
            System.out.println("Key需要16位长度");
            return null;
        }

        byte[] raw=key.getBytes("utf-8");
        SecretKeySpec keySpec=new SecretKeySpec(raw, "AES");
        Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(mode, keySpec);
        byte[] encrypted=cipher.doFinal(src);
        return encrypted;
    }

    public static byte[] Encrypt(byte[] src,String key) throws Exception{
        return Operation(src, key, Cipher.ENCRYPT_MODE);
    }

    public static byte[] Decrypt(byte[] src,String key) throws Exception{
        return Operation(src, key, Cipher.DECRYPT_MODE);
    }

}
主函数
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Main {

    public static void main(String[] args) {
        String key="kkkkkkk123456789";//必须保持16位//

        System.out.println("原数据:");
        String content="Hello,world";
        System.out.println(content);

        byte[] contentByte=content.getBytes();

        System.out.println("原数据转字节:");
        for (int i = 0; i < contentByte.length; i++) {
            System.out.print(contentByte[i]);
        }
        System.out.println();

        try {
            System.out.println("加密后字节:");
            byte[] resultByte=AESUtils.Encrypt(contentByte, key);

            for (int i = 0; i < resultByte.length; i++) {
                System.out.print(resultByte[i]);
            }
            System.out.println();

            System.out.println("解密后字节:");
            byte[] finalByte= AESUtils.Decrypt(resultByte, key);
            for (int i = 0; i < finalByte.length; i++) {
                System.out.print(finalByte[i]);
            }
            System.out.println();
            System.out.println("解密后数据:");
            System.out.println(new String(finalByte));

            String strBase64=new BASE64Encoder().encode(resultByte);
            System.out.println("加密后Base64的数据,这个可在C#解密:");
            System.out.println(strBase64);

            byte[] base64Byte=new BASE64Decoder().decodeBuffer(strBase64);
            System.out.println("Base64解密后的数据:");
            byte[] base64ResultByte=AESUtils.Decrypt(base64Byte, key);
            System.out.println(new String(base64ResultByte));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

C#版本

AES工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace AESTest
{
    class AESHelper
    {

        private static byte[] Operation(byte[] src,string strKey,bool isEncrypt)
        {
            if (string.IsNullOrEmpty(strKey))
                return null;

            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(strKey),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform;

            if(isEncrypt)
            {
                cTransform = rm.CreateEncryptor();
            }
            else
            {
                cTransform = rm.CreateDecryptor();
            }

            byte[] resultArray = cTransform.TransformFinalBlock(src, 0, src.Length);
            return resultArray;
        }

        public static byte[] Encrypt(byte[] src, string strKey)
        {
            return Operation(src, strKey, true);
        }

        public static byte[] Decrypt(byte[] src, string strKey)
        {
            return Operation(src, strKey, false);
        }
    }
}
主函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace AESTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string key = "kkkkkkk123456789";//保持16位
            string content = "Hello,world";
            Console.WriteLine("原数据:");
            Console.WriteLine(content);

            Console.WriteLine("原数据转字节:");
            byte[] contentByte = System.Text.Encoding.Default.GetBytes(content);            
            for (int i = 0; i < contentByte.Length;i++)
            {
                Console.Write(contentByte[i]);
            }
            Console.WriteLine();

            Console.WriteLine("加密后字节:");
            byte[] resultByte = AESHelper.Encrypt(contentByte, key);
            for (int i = 0; i < resultByte.Length; i++)
            {
                Console.Write(resultByte[i]);
            }
            Console.WriteLine();

            Console.WriteLine("解密后字节:");
            byte[] finalByte = AESHelper.Decrypt(resultByte, key);
            for (int i = 0; i < finalByte.Length; i++)
            {
                Console.Write(finalByte[i]);
            }
            Console.WriteLine();

            Console.WriteLine("解密后数据:");
            Console.WriteLine(System.Text.Encoding.Default.GetString(finalByte));

            Console.WriteLine("BASE64加密后数据,Java可用:");
            Console.WriteLine(Convert.ToBase64String(resultByte));

            Console.WriteLine("BASE64解密后数据,Java可用:");
            string javaData = "U/YfVsHyIjczgk9iQfR2VA==";
            byte[] javaBaseArray= Convert.FromBase64String(javaData);
            byte[] finalJavaByte=AESHelper.Decrypt(javaBaseArray, key);

            Console.WriteLine(System.Text.Encoding.Default.GetString(finalJavaByte));

            Console.Read();
        }

    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C#Java 都支持 AES 加密算法,因此可以在两种语言中进行加密和解密。下面是一个示例代码,演示了 C#Java 中如何使用 AES 加密和解密数据。 首先是 Java 中的代码,用于加密数据: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesEncryption { private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String KEY = "0123456789abcdef"; // 16-byte key private static final String IV = "0123456789abcdef"; // 16-byte initialization vector public static String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encrypted); } } ``` 这个代码使用了 AES/CBC/PKCS5Padding 加密算法,采用了 16 字节的密钥和初始化向量。`encrypt()` 方法接受一个字符串参数,并返回加密后的字符串。 接下来是 C# 中的代码,用于解密数据: ```csharp using System; using System.Security.Cryptography; using System.Text; public class AesDecryption { private static readonly byte[] Key = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte key private static readonly byte[] Iv = Encoding.UTF8.GetBytes("0123456789abcdef"); // 16-byte initialization vector public static string Decrypt(string data) { byte[] encryptedData = Convert.FromBase64String(data); using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = Iv; aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.CBC; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length); return Encoding.UTF8.GetString(decrypted); } } } ``` 这个代码使用了相同的 AES/CBC/PKCS5Padding 加密算法和 16 字节的密钥和初始化向量。`Decrypt()` 方法接受一个加密的字符串参数,并返回解密后的字符串。 使用这两个类,可以在 C#Java 中进行 AES 加密和解密操作。注意,密钥和初始化向量需要在两种语言中保持一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值