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