Java C# HTML相互加解密

代码来源(Java代码有改动):http://www.cnblogs.com/lzrabbit/p/3639503.html

因业务需求,需要使用AES加密算法对传输数据进行加密解密操作。一端使用C#,一端使用Java,由于第一次接触C#,在搜索C#的AES算法中是在痛苦从网页到github。。。昨晚找到一点终于找到一个可以使用的。

Java

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

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

/**
 * @author: 已加密
 * @date: 2018/11/3
 * @instructions: AES加密
 */
public class AESEncryptUtils {
    /**
     * 加密 KEY 必须为 16 位
     */
    private static final String KEY = "1234567890000000";
    /**
     * charSet字符集编码
     */
    private static final String charsetName = "utf-8";
    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "AES/ECB/PKCS5Padding";
    /**
     * 加密算法
     */
    public static final String KEY_ALGORITHM = "AES";

    public static String aesEncrypt(String str) {
        if (str == null || KEY == null){
            throw new NullPointerException("加密内容或加密key不能为空");
        }

        try {
            Cipher cipher = Cipher.getInstance(SIGN_ALGORITHMS);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(charsetName), KEY_ALGORITHM));
            byte[] bytes = new byte[1024];
            bytes = cipher.doFinal(str.getBytes(charsetName));
            String result = Base64.encodeBase64String(bytes); /* 解决Base64加密换行问题 */
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "加密失败!";
    }

    public static String aesDecrypt(String str) {
        if (str == null || KEY == null) {
            throw new NullPointerException("解密内容或加密key不能为空");
        }

        try{
            Cipher cipher =  Cipher.getInstance(SIGN_ALGORITHMS);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(charsetName), KEY_ALGORITHM));
            byte[] bytes = new byte[1024];
            bytes = new BASE64Decoder().decodeBuffer(str);
            bytes = cipher.doFinal(bytes);
            return new String(bytes, charsetName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "解密失败!";
    }

}

C#

using System;
using System.Security.Cryptography;
using System.Text;

namespace HelloWorldApplication
{
    class HelloWorld
    {

        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) 
                return null;

            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) 
                return null;
                
            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }
    }

    class my{
        public static void Main(string[] args)
        {
           
                Console.WriteLine(HelloWorld.AesEncrypt("你好","1234567890000000") );
                Console.ReadKey();
        }
    }

}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
 
</head>

<script src="https://cdn.bootcss.com/aes-js/3.1.2/index.js"></script>
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/core.js"></script>
<script src="https://cdn.bootcss.com/crypto-js/3.1.9-1/crypto-js.js"></script>

<body>
 
 
<script>
 
   
 
    var key = CryptoJS.enc.Utf8.parse("1234567887654321");
 
    var plaintText = "1"; // 明文
 

    var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
 
    console.log("加密前:"+plaintText);
    console.log("加密后:"+encryptedData);
 
    encryptedData = encryptedData.ciphertext.toString();
 
    var encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedData);
    var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
 
    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
 
    var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
 
    console.log("解密后:"+decryptedStr);
 
	
	 var pwd = "PCsUFtgog9/qpqmqXsuCRQ==";
    //加密服务端返回的数据
    var decryptedData = CryptoJS.AES.decrypt(pwd, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
	
	console.log("解密服务端返回的数据:"+decryptedStr);
 
</script>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值