//加密
public class Encryption implements IEncryption {
private static final Logger log = LoggerFactory.getLogger(Encryption.class);
/**
* 私钥加密
*
* @param data 内容
* @param privatekey 私钥
* @return 密文
* @throws Exception
*/
@Override
public byte[] encryptByPrivateKey(byte[] data, Key privatekey) throws Exception {
Cipher cipher = Cipher.getInstance(privatekey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privatekey);
return cipher.doFinal(data);
}
/**
* 公钥加密
*
* @param data 内容
* @param publickey 公钥
* @return 密文
* @throws Exception
*/
@Override
public byte[] encryptByPublicKey(byte[] data, Key publickey) throws Exception {
//对数据解密
Cipher cipher = Cipher.getInstance(publickey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publickey);
return cipher.doFinal(data);
}
/**
* 私钥解密
*
* @param data 密文
* @param privatekey 私钥
* @return 明文
* @throws Exception
*/
@Override
public byte[] decryptByPrivateKey(byte[] data, Key privatekey) throws Exception {
//对数据解密
Cipher cipher = Cipher.getInstance(privatekey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privatekey);
return cipher.doFinal(data);
}
/**
* 公钥解密
*
* @param data 密文
* @param publickey 公钥
* @return 明文
* @throws Exception
*/
@Override
public byte[] decryptByPublicKey(byte[] data, Key publickey) throws Exception {
//对数据解密
Cipher cipher = Cipher.getInstance(publickey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publickey);
return cipher.doFinal(data);
}
}
//读取密钥
public class KeyReader implements IKeyReader {
private static final Logger log = LoggerFactory.getLogger(KeyReader.class);
public KeyReader() {
}
/**
* 从密钥文件中读取公钥
*
* @param kstorefile 密钥文件
* @param kstoretype 密钥文件类型,例如:JKS
* @param kstorepwd 密钥文件访问密码
* @param alias 别名
* @return 公钥
*/
@Override
public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias) {
try {
KeyStore ks;
try (FileInputStream in = new FileInputStream(kstorefile)) {
ks = KeyStore.getInstance(kstoretype);
ks.load(in, kstorepwd.toCharArray());
}
if (!ks.containsAlias(alias)) {
log.warn("No such alias in the keystore.");
return null;
}
Certificate cert = ks.getCertificate(alias);
return cert.getPublicKey();
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
log.warn("getPublicKey failure.", ex);
return null;
} catch (FileNotFoundException ex) {
log.warn("getPublicKey failure.", ex);
return null;
} catch (IOException ex) {
log.warn("getPublicKey failure.", ex);
return null;
}
}
/**
* 从密钥文件中读取私钥
*
* @param kstorefile 密钥文件
* @param kstoretype 密钥文件类型,例如:JKS
* @param kstorepwd 密钥文件访问密码
* @param alias 别名
* @return 私钥
*/
@Override
public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias, String keypwd) {
try {
KeyStore ks;
try (FileInputStream in = new FileInputStream(kstorefile)) {
ks = KeyStore.getInstance(kstoretype);
ks.load(in, kstorepwd.toCharArray());
}
if (!ks.containsAlias(alias)) {
log.warn("No such alias in the keystore.");
return null;
}
return (PrivateKey) ks.getKey(alias, keypwd.toCharArray());
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
log.warn("getPrivateKey failure.", ex);
return null;
} catch (FileNotFoundException ex) {
log.warn("getPrivateKey failure.", ex);
return null;
} catch (IOException ex) {
log.warn("getPrivateKey failure.", ex);
return null;
}
}
@Override
public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias) {
try {
KeyStore ks;
try (FileInputStream in = new FileInputStream(kstorefile)) {
ks = KeyStore.getInstance(kstoretype);
ks.load(in, kstorepwd.toCharArray());
}
if (!ks.containsAlias(alias)) {
log.warn("No such alias in the keystore.");
return null;
}
X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
return Base64.encodeBase64String(cert.getEncoded());
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
log.warn("getPublicKey failure.", ex);
return null;
} catch (FileNotFoundException ex) {
log.warn("getPublicKey failure.", ex);
return null;
} catch (IOException ex) {
log.warn("getPublicKey failure.", ex);
return null;
}
}
@Override
public PrivateKey getPrivatekey(String DERfile) {
PrivateKey privateKey = null;
try {
InputStream in = null;
byte[] key = new byte[2048];
in = new FileInputStream(DERfile);
in.read(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
log.error("私钥证书文件格式错误",ex);
} catch (IOException ex) {
log.error(ex.getMessage(),ex);
}
return privateKey;
}
@Override
public PublicKey getPublickey(String CRTfile) {
try {
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
FileInputStream bais = new FileInputStream(CRTfile);
X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
return Cert.getPublicKey();
} catch (CertificateException | FileNotFoundException ex) {
log.warn("getPublicKey failure", ex);
}
return null;
}
private byte[] getPemFileBytes(String fileName) {
BufferedReader br;
byte[] key = null;
try {
br = new BufferedReader(new FileReader(fileName));
String s = br.readLine();
String str = "";
s = br.readLine();
while (s.charAt(0) != '-') {
str += s + "\r";
s = br.readLine();
}
key = Base64.decodeBase64(str);
} catch (Exception ex) {
log.warn("read pem file failure.", ex);
}
return key;
}
}
//签名
public class Sign implements ISignature {
private static final Logger log = LoggerFactory.getLogger(Sign.class);
/**
* RSA签名
*
* @param content 待签内容
* @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
* @param privatekey 私钥
* @return 签名
*/
@Override
public byte[] sign(byte[] content, String algorithm, PrivateKey privatekey) {
try {
//用私钥对信息生成数字签名
Signature stool = Signature.getInstance(algorithm);
stool.initSign(privatekey);
stool.update(content);
return stool.sign();
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
log.warn("sign failure.",ex);
return null;
}
}
/**
* 校验签名
*
* @param content 待验内容
* @param signature 签名
* @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
* @param publickey 公钥
* @return 是否有效签名
*/
@Override
public boolean verify(byte[] content,byte[] signature, String algorithm, PublicKey publickey) {
try {
Signature stool = Signature.getInstance(algorithm);
stool.initVerify(publickey);
stool.update(content);
//验证签名是否正常
return stool.verify(signature);
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
log.warn("verify failure.",ex);
return false;
}
}
}