[JAVA]前後端加解密技術(以圖片AES爲例,其他內容的其他加密方法也可以)

1. 前端AES加解密

1) 使用技術:開源JS(CryptoJS)

     官網:https://github.com/brix/crypto-js

2) demo

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="./comm/crypto-js/crypto-js.js"></script>
<script type="text/javascript" src="./comm/crypto-js/aes.js"></script>
<script>
	window.onload = function() {
		var f = document.getElementById("file");

		//this.files即獲取input中上傳的file對象 是個數組   
		f.onchange = function() {
			//獲取文件對象  
			var file = this.files[0];
			//使用fileReader對文件對象進行操作  
			var reader = new FileReader();
			//用於圖片顯示不需要傳入後臺,reader.result的結果是base64編碼數據,直接放入img的src中即可  
			reader.readAsDataURL(file);
			reader.onload = function() {
				// 1.取得加密前的明文數據(base64格式)
				var src = this.result.split(',')[1];
				$("#de").text(src);
				$("#del").text(src.length);

				// 2.加密處理
				//var key = CryptoJS.enc.Hex.parse('1234567890123456')
				var key = CryptoJS.enc.Utf8.parse('1234567890123456');
				var iv = CryptoJS.enc.Utf8.parse("0123456789ABCDEF")
				console.log('原字符串:', src);
				var enc = CryptoJS.AES.encrypt(src, key, {
					iv : iv,
					mode : CryptoJS.mode.CBC,
					padding : CryptoJS.pad.Pkcs7
				})

				var enced = enc.ciphertext.toString()
				$("#en").text(enced);
				$("#enl").text(enced.length);

				// 3.解密處理
				var dec = CryptoJS.AES.decrypt(
						CryptoJS.format.Hex.parse(enced), key, {
							iv : iv,
							mode : CryptoJS.mode.CBC,
							padding : CryptoJS.pad.Pkcs7
						});

				$("#de2").text(CryptoJS.enc.Utf8.stringify(dec));
				$("#de2l").text(CryptoJS.enc.Utf8.stringify(dec).length);
			}
		}

	}
</script>
</head>
<body>
	<input type="file" id="file">
	<!-- 只能上傳單個文件 -->
	<br> 明文:
	<br>
	<textarea id="de" style="width: 1100px; height: 300px"></textarea>
	<span id="del"></span>
	<br> 密文:
	<br>
	<textarea id="en" style="width: 1100px; height: 300px"></textarea>
	<span id="enl"></span>
	<br> 明文(解密後):
	<br>
	<textarea id="de2" style="width: 1100px; height: 300px"></textarea>
	<span id="de2l"></span>

</body>
</html>

2. Java端AES加解密

1) 使用技術:開源Jar(bcprov-ext-jdk15on-1.61.jar)

     

<dependency>	
  <groupId>org.bouncycastle</groupId>	
  <artifactId>bcprov-ext-jdk15on</artifactId>	
  <version>1.61</version>	
</dependency>	

2) demo

package encrypt.img;

import java.io.File;
import java.security.Security;

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

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;

public class AesCbcTest {
	public static final String KEY_ALGORITHM = "AES";
	// 加解密算法/模式/填充方式
	// 可以任意選擇,爲了方便後面與iOS端的加密解密,採用與其相同的模式與填充方式
	// ECB模式只用密鑰即可對數據進行加密解密,CBC模式需要添加一個參數iv
	public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

	@Before
	public void initDH() {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	}

	@Test
	public void testAesDecrvpt() throws Exception {
		// 1.初始化key和iv
		String basePath = this.getClass().getResource("/").getPath();
		String enc = FileUtils.readFileToString(new File(basePath + "\\data\\密文.txt"), "utf-8");

		// 2.aes解密
		byte[] key = "1234567890123456".getBytes("utf-8");
		byte[] iv = "0123456789ABCDEF".getBytes("utf-8");
		SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
		byte[] hexBytes = hexStringToBytes(enc);
		byte[] plainBytes = cipher.doFinal(hexBytes);

		// 3.輸出結果
		String de = new String(plainBytes, "utf-8");
		FileUtils.writeStringToFile(new File(basePath + "\\data\\明文(解密後).txt"), de, "utf-8");
		FileUtils.writeByteArrayToFile(new File(basePath + "\\data\\明文(解密後).jpg"), org.springframework.util.Base64Utils.decode(plainBytes));
	}

	/**
	 * 將16進制字符串裝換爲byte數組
	 * 
	 * @param hexString
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] b = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			b[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return b;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}

 

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