欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JS客户端RSA加密,Java服务端解密

程序员文章站 2022-07-13 12:19:04
...

一、JS的RSA加密

JS在RSA加密方面做的比较好的是jsencrypt,大家可以在附件中下载页面jsencrypt加解密的小例子。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
    <script type="text/javascript">     
        $(function () {
            $('#testme').click(function () {
				var encrypt = new JSEncrypt();
				var pubKey = $('#pubkey').val();
				var privkey = $('#privkey').val();
				encrypt.setPublicKey(pubKey);	
				var encrypted = encrypt.encrypt($('#passwd').val());
				console.log(encrypted);				
				var decrypt = new JSEncrypt();
				decrypt.setPrivateKey($('#privkey').val());
				var uncrypted = decrypt.decrypt(encrypted);		
				if (uncrypted == $('#passwd').val()) {
					alert('It works!!!');
				}
				console.log(uncrypted);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
			<label for="pubkey">Public Key</label><br/>
			<textarea id="pubkey" rows="15" cols="65">30819f300d06092a864886f70d010101050003818d0030818902818100994614bb2c14a701a7cfd73d107751110dde9f78bdbc9b97eb4e9ccfd587fa3df80c699a345ea1577fd76a191419a10891919b094e42f0bc3fde17c06b10c8b59e3e099426e376499669b7d9b1f17bb8d604b4cca60a39e09de3d51fbe85886240957ad2dbeffcef3427d7f4ca59bbef23ab35722a07fc9d5ef74b87926a579b0203010001</textarea><br/>
			<br />
			<label for="privkey">Private Key</label><br/>
			<textarea id="privkey" rows="15" cols="65">30820277020100300d06092a864886f70d0101010500048202613082025d02010002818100994614bb2c14a701a7cfd73d107751110dde9f78bdbc9b97eb4e9ccfd587fa3df80c699a345ea1577fd76a191419a10891919b094e42f0bc3fde17c06b10c8b59e3e099426e376499669b7d9b1f17bb8d604b4cca60a39e09de3d51fbe85886240957ad2dbeffcef3427d7f4ca59bbef23ab35722a07fc9d5ef74b87926a579b02030100010281804a619415f12264998d1273e5926414d72ddfe78bf4a7deea2eab0bb6606d88a72205040a6d77aedc8391ca4f394de6b3fdd0a76830ae939d0771841d40d7f84e44d949c817e1c9af3d4f48ae82a2b9c51dd5844bc2ef7549497cd1fb6de425cabc881ac709a2fa52af8693f21ea68abe3a6ede68686bf77d3544435860708481024100fd1897e0be000b41a0f8274611209e81c0a151a3d5a263a598c098a97627ee2f95c09fc381f46fc08f304a428df465783f761a74fed0bd4de1c99878bd434b0b0241009b0848d4d96707152aef601afda166f4c2af424ed85d56b93e34d1f3a09f204eeaf2082cd73ee88b63c1eace10cba635f0b0eddab1ed0890d7ddbfb4cf9b7fb1024100ae5d29151e10adb09313230b7475427e25957dc71f40f6e178f106bb88b94db0debc8bd4874d3d482ddd98eb6d1cb86335654a28dbfc36ced704a9d4549f6dad0240245e4727977071dae75d8c4008abaa4954ba6465b69ffece29e79e30f6c71d7f25e26d4487a1fc4f66b180f1a24303d4b787e9e459c4ef337b504bbe90cd3ba1024100d91056b9823941b53d593f253236ba75c382efa5b88365124c70850e8c965e18262b0664440967024d3fe158b1f1c066df8f9031ebc5f2886aa07514c8fe77fb</textarea>
			<br/>
            <label for="input">Text to encrypt:</label><br />
            <input id="passwd" name="passwd" ></input><br />
            <input id="testme" type="button" value="submit" /><br />
        </div>
    </form>
</body>
</html>

 

二、java服务端解密

1、引入所需jar

		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.4</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk15on</artifactId>
			<version>1.52</version>
		</dependency>

 2、添加RSAUtils工具类

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RSA表单加密
 * 
 * @author xx
 * @version 1.0
 * @since 2013-11-10
 */
public class RSAUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
	
	private static String keyPath = null;
	static {
		keyPath = RSAUtils.class.getResource("/").getPath() + "RSAKey.txt";
		try {
			@SuppressWarnings("unused")
			RSAPublicKey rsap = (RSAPublicKey) RSAUtils.generateKeyPair().getPublic();
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	/**
	 * * 生成密钥对 *
	 * 
	 * @return KeyPair 
	 * @throws NoSuchAlgorithmException 
	 * @throws IOException *
	 * @throws EncryptException
	 */
	public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, IOException {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
				new org.bouncycastle.jce.provider.BouncyCastleProvider());
		final int KEY_SIZE = 1024;// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
		keyPairGen.initialize(KEY_SIZE, new SecureRandom());
		KeyPair keyPair = keyPairGen.generateKeyPair();
		saveKeyPair(keyPair);
		return keyPair;
	}

	public static KeyPair getKeyPair() throws IOException, ClassNotFoundException {
		FileInputStream fis = new FileInputStream(keyPath);
		ObjectInputStream oos = new ObjectInputStream(fis);
		KeyPair kp = (KeyPair) oos.readObject();
		oos.close();
		fis.close();
		return kp;
	}

	public static void saveKeyPair(KeyPair kp) throws IOException {

		FileOutputStream fos = new FileOutputStream(keyPath);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		// 生成密钥
		oos.writeObject(kp);
		oos.close();
		fos.close();
	}

	/**
	 * * 生成公钥 *
	 * 
	 * @param modulus *
	 * @param publicExponent *
	 * @return RSAPublicKey *
	 * @throws NoSuchAlgorithmException, InvalidKeySpecException
	 */
	public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent)throws NoSuchAlgorithmException, InvalidKeySpecException {
		KeyFactory keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

		RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
		return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
	}

	/**
	 * * 生成私钥 *
	 * 
	 * @param modulus *
	 * @param privateExponent *
	 * @return RSAPrivateKey *
	 */
	public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws NoSuchAlgorithmException, InvalidKeySpecException {
		KeyFactory keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

		RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
		return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
	}

	/**
	 * * 加密 *
	 * 
	 * @param key 加密的密钥 *
	 * @param data 待加密的明文数据 *
	 * @return 加密后的数据 
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws ShortBufferException *
	 * @throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException
	 */
	public static byte[] encrypt(PublicKey pk, byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
		Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(Cipher.ENCRYPT_MODE, pk);
		int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
		// 加密块大小为127
		// byte,加密后为128个byte;因此共有2个加密块,第一个127
		// byte第二个为1个byte
		int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
		int leavedSize = data.length % blockSize;
		int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
		byte[] raw = new byte[outputSize * blocksSize];
		int i = 0;
		while (data.length - i * blockSize > 0) {
			if (data.length - i * blockSize > blockSize)
				cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
			else
				cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
			// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
			// ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
			// OutputSize所以只好用dofinal方法。

			i++;
		}
		return raw;
		
	}

	/**
	 * * 解密 *
	 * 
	 * @param key 解密的密钥 *
	 * @param raw 已经加密的数据 *
	 * @return 解密后的明文 
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 * @throws IOException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException *
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	public static byte[] decrypt(PrivateKey pk, byte[] raw) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
		Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
		cipher.init(cipher.DECRYPT_MODE, pk);
		int blockSize = cipher.getBlockSize();
		ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
		int j = 0;

		while (raw.length - j * blockSize > 0) {
			bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
			j++;
		}
		return bout.toByteArray();
	}

	public static String getRSADecrypt(String str) {
		byte[] en_result = hexStringToBytes(str);
		byte[] de_result = {};
		try {
			de_result = RSAUtils.decrypt(RSAUtils.getKeyPair().getPrivate(), en_result);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		StringBuffer sb = new StringBuffer(new String(de_result));
		return sb.reverse().toString();
	}

	/**
	 * 16进制 To byte[]
	 * 
	 * @param hexString
	 * @return byte[]
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**
	 * Convert char to byte
	 * 
	 * @param c char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

}

 

3、添加页面表单解密工具类FormDecryptUtils

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 页面表单解密工具类
 * <p>
 * JS版RSA加密请参考:https://github.com/travist/jsencrypt 
 * </p>
 * @author lh
 * @since 2017-05-16
 * @version 3.0
 *
 */
public class FormDecryptUtils {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FormDecryptUtils.class);

	//private static final String BASE64PUBKEY = "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DB+MYkCdi4rouvvS7V8f50o=";
	private static final String KEY_ALGORITHM = "RSA";
	
	/** 安全服务提供者 */
	private static final Provider PROVIDER = new BouncyCastleProvider();
	
	/**
	 * 解密
	 * @param text
	 *            Base64编码字符串
	 * @return 解密后的数据
	 */
	public static String decrypt(String text) {
		byte[] data = null;
		try {
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
			//cipher.init(Cipher.DECRYPT_MODE, RSAUtils.getKeyPair().getPrivate());
			cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(BASE64PRIKEY));
			data = cipher.doFinal(Base64.decodeBase64(text));
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			return null;
		}
		return data != null ? new String(data) : null;
	}
	
	/**
	 * 取得公钥对象
	 * @param key	公钥key
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeySpecException
	 */
	public static PublicKey getPublicKey(String key){  
		// 解密由base64编码的公钥     
        byte[] keyBytes = Base64.decodeBase64(key.getBytes());     
        // 构造X509EncodedKeySpec对象     
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        try{
        	// KEY_ALGORITHM 指定的加密算法     
        	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);         	
        	return keyFactory.generatePublic(keySpec);          	
        } catch (NoSuchAlgorithmException|InvalidKeySpecException e) {
			LOGGER.error(e.getMessage(),e);
			return null;
		}
    }
	/**
	 * 取得私钥对象
	 * @param key	私钥key
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String key){
		byte[] keyBytes = Base64.decodeBase64(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory;
		try {
			keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			return keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException|InvalidKeySpecException e) {
			LOGGER.error(e.getMessage(),e);
			return null;
		}
	}
	
	/**
	 * 取得公钥key(base64加密)
	 * @return
	 */
	public static String getPublicKey(){
		try {
			return new String(Base64.encodeBase64(RSAUtils.getKeyPair().getPublic().getEncoded()));
		} catch (ClassNotFoundException | IOException e) {
			LOGGER.error(e.getMessage(),e);
			return null;
		}
	}
	
	/**
	 * 取得私钥key(base64加密)
	 * @return
	 */
	public static String getPrivateKey(){
		try {
			return new String(Base64.encodeBase64(RSAUtils.getKeyPair().getPrivate().getEncoded()));
		} catch (ClassNotFoundException | IOException e) {
			LOGGER.error(e.getMessage(),e);
			return null;
		}
	}

}

 

4、对js加密的内容解密

model.setLoginPwd(FormDecryptUtils.decrypt(model.getLoginPwd()));

 

相关标签: rsa java