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

阅读更多

一、JS的RSA加密

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




    
    
    
    
    


    








 

二、java服务端解密

1、引入所需jar

		
			commons-codec
			commons-codec
			1.4
			compile
		
		
			org.bouncycastle
			bcprov-jdk15on
			1.52
		

 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;

/**
 * 页面表单解密工具类
 * 

* JS版RSA加密请参考:https://github.com/travist/jsencrypt *

* @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 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfU3jYhR8QzD+0x7SG/gGuQ9w3JOlJJ2CNbN8eAdiDKCPZ9gektP52tZE31txQ5NQraqW13+un16jJTs/iumQVw2n9L5ZmXCDZueNWrOwaaTA6vHs9KD9SgEVM6+7ml0NJpRBeBEr58Dtjzh51f6YDVn0nJeJ6pr0GdWXi3kNqMQIDAQAB"; private static final String BASE64PRIKEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9TeNiFHxDMP7THtIb+Aa5D3Dck6UknYI1s3x4B2IMoI9n2B6S0/na1kTfW3FDk1CtqpbXf66fXqMlOz+K6ZBXDaf0vlmZcINm541as7BppMDq8ez0oP1KARUzr7uaXQ0mlEF4ESvnwO2POHnV/pgNWfScl4nqmvQZ1ZeLeQ2oxAgMBAAECgYAXUQjzbu/v7mQ4Wa2Sv+ORFD9LFqzJVujraY5xfsWn1B0DDd1qfk5rIwFAkcImWIawX+gmaMG9C3OZGl6UCMESrr+0E7cQceyoz3vHuY2uRuJZq7yfnQyJKmPZ5kf+tY4T9DgfgYvt/J+xz9X5IGQYvUiLpZd9iXLrQYHqoehJbQJBAOOzxbIfJTlF5EU2dKDzM9uKdKeDiZvt4k6tXHM107fstk1rz/NA78IyorRs/uj9hPH82WIwfC9XNMwBhK6+0BMCQQCzIFj6HL0XuNqZoKcTb2O45eYpudIXl2Q2DPKu9pkrmh5fFnSqNhEa2fO/PaYktJTiL0vdm/hNX3KTEr2xdI0rAkEAkwJV+RIyri95mVX3JpLeQDe76Qr7pTiIi9NRhPCTqIOjj4iz0ZFzOiYG9gYI7dQAKVvd3Y8AHnBnHe89ArUfEQJBAIIDaJGhal5dfc0kHiCtKOR7eaOvjB4zdDkHDN6Rfnt3UbQSyHsC40dqCtE0HfNmXuoNCjO/kWoXbUHyyFyVDCECQD7TBTc9JDQ1fJItyL/QrqmXH4ixOjaHS5ZC0eeWxkHdlsTbzibonqk6YC9R0628DB+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()));

 

  • page_rsaEncrypt.zip (37.6 KB)
  • 下载次数: 2

你可能感兴趣的:(rsa,java)