`
hbxflihua
  • 浏览: 660191 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

阅读更多

一、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 = "M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B+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加密 js客户端加密 java服务端servlet解密

    提供加密,解密,生成密钥对等方法。js客户端用公钥加密 java服务端servlet堆用私钥解密 完整的代码 直接可以部署运行

    RSA加密解密 JS加密 JAVA解密 【完美版】

    经过本人修改,简化并完善了别人的代码,使其更加的容易理解和学习! 此为一个完整的项目,...功能:服务端随机生成密钥,JS用公钥加密,服务端用私钥解密。用到的JS加密文件是从官网下载的最新版,速度快,稳定性好!

    RSA浏览器加密,服务端解密

    NULL 博文链接:https://songfeng-123.iteye.com/blog/2258830

    RSA算法JAVA公钥加密,C#私钥解密

    可以直接运行成功的RSA加密解密示例 JAVA端采用公钥加密,服务端C#采用私钥解密。

    rsa加密(js加密java解密)

    rsa加密技术是js前端加密,服务端解密,很适合密文加密传输

    AES+RSA加密客户端

    使用cryptopp编写AES+RSA加解密算法,客户端生成AES密钥,然后用RSA加密后发到服务端解密

    java模仿QQ通信实现RSA加密解密

    java 模仿QQ通信 socket编程,多个客户端与服务端连接,服务端起转发作用,客户端可与另外一个指定客户端通信 RSA加密解密 消息摘要 数字签名

    AES+RSA加解密服务端

    AES+RSA加解密服务端,接收到客户端发过来的两种加密后的AES密钥,并解密的到保存之

    Java实现RSA加密解密,数字证书生成与验证

    Java实现RSA加密解密,数字证书生成与验证,模拟两个端通信,AB双方通信,客户端A把需要传输的文件MD5值用自己的私钥生成数字签名,连同明文用服务端B的公钥加密后传送给服务端B,服务端B用私钥解密验证数字签名,并计算...

    RSA的jar包,js和RSA的java工具类

    jsp rsa密码加密技术,jsp页面的js,java服务端的java包,加解密的工具类

    flutter加密java解密

    解决 flutter =&gt; java后台 =&gt; 硬件 相联系的需求 (需保证App端、服务端、硬件三方加密结果一致)

    RSA加密全流程以及文档

    在客户端浏览器,Javascript使用RSA算法,以公钥对密码进行加密,服务端使用相应的私钥进行解密。一般用于注册时或登录时填写的密码。 1. [文件] security.js ~ 19KB 2. [文件] RSAUtils.java ~ 15KB 说明文档

    基于Python语言、RSA非对称加密的IRC聊天室客户端源码与应用程序

    在RSA加密通信中,发送端和接收端各有一对密钥,且不相同。发送信息时,发送端用接收端的密钥进行加密,接收端用自身保存的私钥进行解密。由于能够解密的私钥只保存在接收端,因此只有接收端能解开加密内容,如此...

    C#代码RSA加密、解密

    如果是要对发送的消息进行加密和解密,加密时用公钥,解密时用私钥,即使密文被窃取也无法破解。  如果是要对软件进行注册,生成注册码,则服务端将用户的硬盘号用私钥加密,客户端用公钥解密,解密后将客户端的...

    RSA 前后端加密方案&密钥生成工具

    rsa加密技术是js前端加密,服务端解密,很适合密文加密传输

    AWD-Web 工具资料集合.zip

    rsa加密后门服务端 解密攻击payload并返回执行结果 rsa_attack.py ------rsa木马测试 测试rsa客户端和服务端是否可以实现互相通信 nodie.php ------不死马 主要负责写入rsa不死马 crontab.py ------定时任务写入...

    PHP+JS+rsa数据加密传输

    所以很多网站选择了模拟SSL的做法,使用RSA来对密码等安全信息进行公钥加密,服务端用私钥解密。 通常是对密码进行加密,本文也拿密码加密为例。 网上相关信息太少,折腾了几天,终于有眉目了,先贴代码,关键...

Global site tag (gtag.js) - Google Analytics