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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章