[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);
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值