前端/後端(Java)的AES加密和解密

前端代碼

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Insert title here</title>
		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
		<script type="text/javascript" src="http://react.file.alimmdn.com/aes.js"></script>
		<script type="text/javascript" src="js/aes.js"></script>
	</head>

	<body>
		<textarea id="textareaid1" cols="50" rows="10">這裏輸入內容</textarea><br>
		<input type="button" value="加密" onclick="enCode()" /><br>
		<textarea id="textareaid2" cols="50" rows="10">這裏顯示內容</textarea><br>
		<input type="button" value="解密" onclick="deCode()" /><br>
		<textarea id="textareaid3" cols="50" rows="10">這裏顯示內容</textarea><br>
	</body>
	<script type="text/javascript">
		function getSecret(str) {
			var str_s=str;
			var encodeData = window.btoa(window.encodeURIComponent(str)) 
			while(encodeData.length < 16) {
				str_s+="_";
				encodeData = window.btoa(window.encodeURIComponent(str_s)) 
			}
			var secret = encodeData.slice(encodeData.length - 16, encodeData.length)
			return secret;

		}
		function enCode() {
			var value = $("#textareaid1").val();
			var envalue = encrypt(value, getSecret("XXXXXXXXX"));
			console.log(window.btoa(window.encodeURIComponent(envalue)))
			$("#textareaid2").text(window.btoa(window.encodeURIComponent(envalue)));
		}

		function deCode() {
			var value = $("#textareaid2").val();
			console.log(window.decodeURIComponent(window.atob(value)))
			var devalue = decrypt(window.decodeURIComponent(window.atob(value)), getSecret("XXXXXXXXX"));
			$("#textareaid3").text(devalue);
		}

		/***************************************************** 
		* AES加密 
		* @param content 加密內容 
		* @param key 加密密碼,由字母或數字組成 
		      此方法使用AES-128-ECB加密模式,key需要爲16位 
		      加密解密key必須相同,如:abcd1234abcd1234 
		* @return 加密密文 
		****************************************************/
		function encrypt(content, key) {
			var sKey = CryptoJS.enc.Utf8.parse(key);
			var sContent = CryptoJS.enc.Utf8.parse(content);
			var encrypted = CryptoJS.AES.encrypt(sContent, sKey, {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			});
			return encrypted.toString();
		}

		/***************************************************** 
		* AES解密 
		* @param content 加密密文 
		* @param key 加密密碼,由字母或數字組成 
		      此方法使用AES-128-ECB加密模式,key需要爲16位 
		      加密解密key必須相同,如:abcd1234abcd1234 
		* @return 解密明文 
		****************************************************/
		function decrypt(content, key) {
			var sKey = CryptoJS.enc.Utf8.parse(key);
			var decrypt = CryptoJS.AES.decrypt(content, sKey, {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			});
			return CryptoJS.enc.Utf8.stringify(decrypt).toString();
		}
	</script>

</html>

    這裏我會根據base64獲取密鑰,然後通過密鑰對密碼進行AES加密最後返回時進行base64加密,然後再解密時先對密文進行base64解密再用AES解密。可以看到前端已經能正常的編解碼。

後端代碼

pom文件:

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

工具類:

package com.example.test;

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

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;

/**
 * @Classname AesUtils
 * @Description TODO
 * @Date 2019/9/18 11:15
 * @Created zzf
 */
public class AesUtils {

    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * aes解密
     *
     * @param encrypt 內容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt, String key) {
        try {
            return aesDecrypts(encrypt, key);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * aes加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content, String key) {
        try {
            return aesEncrypts(content, key);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 將byte[]轉爲各種進制的字符串
     *
     * @param bytes byte[]
     * @param radix 可以轉換進制的範圍,從Character.MIN_RADIX到Character.MAX_RADIX,超出範圍後變爲10進制
     * @return 轉換後的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 這裏的1代表正數
    }

    /**
     * base 64 encode
     *
     * @param bytes 待編碼的byte[]
     * @return 編碼後的base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解碼的base 64 code
     * @return 解碼後的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }


    /**
     * AES加密
     *
     * @param content    待加密的內容
     * @param encryptKey 加密密鑰
     * @return 加密後的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }


    /**
     * AES加密爲base 64 code
     *
     * @param content    待加密的內容
     * @param encryptKey 加密密鑰
     * @return 加密後的base 64 code
     * @throws Exception
     */
    public static String aesEncrypts(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     *
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密鑰
     * @return 解密後的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * 將base 64 code AES解密
     *
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密鑰
     * @return 解密後的string
     * @throws Exception
     */
    public static String aesDecrypts(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

}

具體實現:

package com.example.test;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.net.URLEncoder;

import static com.example.test.AesUtils.aesDecrypt;

/**
 * @Classname TestController
 * @Description TODO
 * @Date 2019/9/18 13:40
 * @Created zzf
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/{key}/{password}")
    public String test(@PathVariable("key") String key, @PathVariable("password") String password) {
        //解碼獲取密碼
        final Base64 base64 = new Base64();
        String text = key;
        String textPassword = password;
        try {
            byte[] textByte = text.getBytes("UTF-8");
            byte[] textPasswordByte = textPassword.getBytes("UTF-8");
            //編碼
            String encodedText = base64.encodeToString(textByte);
            //解碼
            String encodedPassword = URLDecoder.decode(new String(base64.decode(textPasswordByte), "UTF-8"), "UTF-8");
            while (encodedText.length() < 16) {
                text += "_";
                textByte = URLEncoder.encode(text,"UTF-8").getBytes("UTF-8");
                encodedText = base64.encodeToString(textByte);
            }
            String keys = encodedText.substring(encodedText.length() - 16);
            password = aesDecrypt(encodedPassword, keys);
        } catch (Exception e) {

        }
        return password;
    }

}

GET /test/XXXXXXXXX/MGZnbWZ5SzZtU0hNZFdxRkVqUVcxWlFqT2w3ZE9IVlJuZ2pqcEolMkZlT2RRJTNE HTTP/1.1
Host: localhost:8080
User-Agent: PostmanRuntime/7.17.1
Accept: */*
Cache-Control: no-cache
Postman-Token: d9233144-9ffd-47ba-9d9e-127bb193866b,c86bfa8b-629b-4b04-b724-f1347cfe8b2e
Host: localhost:8080
Accept-Encoding: gzip, deflate
Cookie: JSESSIONID=328CB1D49A0CD2A66FF30611B2543998
Connection: keep-alive
cache-control: no-cache

ok~~具體各位請自行Debug!

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