package com.sdyc.datahub.api.utils; /** *
 *
 * Created by zhenqin.
 * User: zhenqin
 * Date: 17/1/10
 * Time: 14:41
 * Vendor: NowledgeData
 * To change this template use File | Settings | File Templates.
 *
 * 
* * @author zhenqin */ import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMReader; import javax.crypto.Cipher; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.nio.ByteBuffer; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; /** *

* RSA公钥/私钥/签名工具包 *

* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 *

* */ public class RSAUtils { /** * 加密算法RSA */ public static final String KEY_ALGORITHM = "RSA"; /** * 签名算法 */ public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /** * 获取公钥的key */ public static final String PUBLIC_KEY = "LocatorPublicKey"; /** * 获取私钥的key */ public static final String PRIVATE_KEY = "LocatorPrivateKey"; /** * RSA最大加密明文大小 */ public static final int MAX_ENCRYPT_BLOCK = 1024; /** * RSA最大解密密文大小 */ public static final int MAX_DECRYPT_BLOCK = 128; static { Security.addProvider(new BouncyCastleProvider()); } static class CipherXX { final Cipher decryptCipher; final Cipher encryptCihper; CipherXX(Key key) { try { KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); if(key instanceof PublicKey) { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key.getEncoded()); Key publicK = keyFactory.generatePublic(x509KeySpec); decryptCipher = Cipher.getInstance(keyFactory.getAlgorithm()); decryptCipher.init(Cipher.DECRYPT_MODE, publicK); // 对数据加密 encryptCihper = Cipher.getInstance(keyFactory.getAlgorithm()); encryptCihper.init(Cipher.ENCRYPT_MODE, publicK); } else { PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key.getEncoded()); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); decryptCipher = Cipher.getInstance(keyFactory.getAlgorithm()); decryptCipher.init(Cipher.DECRYPT_MODE, privateK); encryptCihper = Cipher.getInstance(keyFactory.getAlgorithm()); encryptCihper.init(Cipher.ENCRYPT_MODE, privateK); } } catch (Exception e) { throw new IllegalStateException(e); } } public Cipher getDecryptCipher() { return decryptCipher; } public Cipher getEncryptCihper() { return encryptCihper; } } /** * Thread Local */ protected final static ThreadLocal THREAD_LOCAL = new ThreadLocal(); private RSAUtils() { } private static Cipher getCipher(Key key, int mode) throws Exception { Map KEY_CIPHER_MAP = THREAD_LOCAL.get(); boolean put = false; if(KEY_CIPHER_MAP == null) { KEY_CIPHER_MAP = new HashMap(3); put = true; } CipherXX cipher = KEY_CIPHER_MAP.get(key); if(cipher == null) { cipher = new CipherXX(key); KEY_CIPHER_MAP.put(key, cipher); } if(put) THREAD_LOCAL.set(KEY_CIPHER_MAP); return mode == Cipher.ENCRYPT_MODE ? cipher.getEncryptCihper() : cipher.getDecryptCipher(); } /** *

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */ public static Map genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); PublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map keyMap = new HashMap(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** *

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */ public static Map genFileKeyPair(File privateKeyFile) throws Exception { PEMReader reader = null; try { reader = new PEMReader(new FileReader(privateKeyFile), null); KeyPair keyPair = (KeyPair) reader.readObject(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Map keyMap = new HashMap(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } finally { IOUtils.closeQuietly(reader); } } /** *

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */ public static PublicKey genPublicKey(File publicKeyFile) throws Exception { PEMReader reader = null; try { reader = new PEMReader(new FileReader(publicKeyFile), null); return (PublicKey) reader.readObject(); } finally { IOUtils.closeQuietly(reader); } } /** *

* 用私钥对信息生成数字签名 *

* * @param data 已加密数据 * @param privateKey 私钥(BASE64编码) * * @return * @throws Exception */ public static String sign(byte[] data, PrivateKey privateKey) throws Exception { PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64.encodeBase64String(signature.sign()); } /** *

* 校验数字签名 *

* * @param data 已加密数据 * @param publicKey 公钥(BASE64编码) * @param sign 数字签名 * * @return * @throws Exception * */ public static boolean verify(byte[] data, PublicKey publicKey, String sign) throws Exception { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data); return signature.verify(Base64.decodeBase64(sign)); } /** *

* 私钥解密 *

* * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, PrivateKey privateKey) throws Exception { Cipher cipher = getCipher(privateKey, Cipher.DECRYPT_MODE); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** *

* 公钥解密 *

* * @param encryptedData 已加密数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, PublicKey publicKey) throws Exception { Cipher cipher = getCipher(publicKey, Cipher.DECRYPT_MODE); int inputLen = encryptedData.length; ByteBuffer buffer = ByteBuffer.allocate(MAX_ENCRYPT_BLOCK); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } buffer.put(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } buffer.flip(); byte[] dst = new byte[buffer.limit()]; buffer.get(dst, 0, buffer.limit()); return dst; } /** *

* 公钥加密 *

* * @param data 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = getCipher(publicKey, Cipher.ENCRYPT_MODE); int inputLen = data.length; ByteBuffer buffer = ByteBuffer.allocate(MAX_ENCRYPT_BLOCK); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } buffer.put(cache); i++; offSet = i * MAX_ENCRYPT_BLOCK; } buffer.flip(); byte[] dst = new byte[buffer.limit()]; buffer.get(dst, 0, buffer.limit()); return dst; } /** *

* 私钥加密 *

* * @param data 源数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = getCipher(privateKey, Cipher.ENCRYPT_MODE); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } public static void main(String[] args) throws Exception { String str = "srcbabababababab"; File privateKeyFile = new File("/Volumes/Media/Workspace/美亚DataHub/id_rsa.keystore"); File publicKeyFile = new File("/Volumes/Media/Workspace/美亚DataHub/id_rsa.keystore.pub"); Map keyPair = genFileKeyPair(privateKeyFile); PrivateKey privateKey = (PrivateKey) keyPair.get(PRIVATE_KEY); PublicKey publicKeyX = (PublicKey) keyPair.get(PUBLIC_KEY); PublicKey publicKey = genPublicKey(publicKeyFile); System.out.println("====== encoding by private key, decoding by public key======"); byte[] x = encryptByPrivateKey(str.getBytes(), privateKey); System.out.println("encode: " + Base64.encodeBase64String(x)); System.out.println("decode: " + new String(decryptByPublicKey(x, publicKeyX))); System.out.println("decode: " + new String(decryptByPublicKey(x, publicKey))); System.out.println("====== encoding by public key, decoding by private key======"); x = encryptByPublicKey(str.getBytes(), publicKey); System.out.println("encode: " + Base64.encodeBase64String(x)); System.out.println("decode: " + new String(decryptByPrivateKey(x, privateKey))); System.out.println("====== encoding by public key, decoding by private key======"); x = encryptByPublicKey(str.getBytes(), publicKey); System.out.println("encode: " + Base64.encodeBase64String(x)); System.out.println("encode: " + Base64.encodeBase64String(x)); System.out.println("encode: " + Base64.encodeBase64String(x)); System.out.println("decode: " + new String(decryptByPrivateKey(x, privateKey))); System.out.println("======================"); } }