一、加签
通过私钥对需要加签的字符串进行加签
// 签名算法
public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
// 加密算法RSA
public static final String KEY_ALGORITHM = "RSA";
public String sign(String str, String privateKey) throws Exception{
byte[] data = str.getBytes();
PrivateKey privateKey = getPrivateKeyFromString(privateKey);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateKey);
signature.update(data);
byte[] bytes = signature.sign();
return Base64.encodeBase64string(bytes);
}
二、验签
public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
public boolean verifySign(String str, String publicKey, String sign) throws Exception{
byte[] data = str.getBytes();
byte[] signBytes = Base64.decodeBase64(sign);
PublicKey publicKey = getPublicKeyFromString(publicKey);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(signBytes);
}
三、加密
1、生成秘钥aesKey
public String getAESRandomKey(){
Long longValue = random.nextLong();
return string.format("%016x",longValue);
}
2、使用秘钥aesKey对业务字段进行加密bizData
public String encryptByAES(String data, String aesKey) throws Exception{
byte[] dataBytes = data.getBytes();
byte[] aesKeyBytes = aesKey.getBytes();
Cipher cipher =Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");
cipher.init(cipher.ENCRYPT_MODE, keySpec);
byte[l ret = cipher.doFinal(dataBytes);
return Base64.encodeBase64String(ret);
}
3、使用公钥对aesKey进行加密
public String getRandomKey(String aesKey, String publicKey) throws Exception{
PublicKey key = getPblicKeyFromString(publicKey);
byte[] aesKeyBytes = aesKey.getBytes();
Cipher cipher = cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE, key);
byte[] output = cipher.doFinal(input);
return Base64.encodeBase64string(output);
}
四、解密
1、使用私钥privateKey对randomKey解密获取AES秘钥aesKey
public String decryptByRSA(String randomKey, String privateKey)throws Exception{
Privatekey key= getPrivateKeyFromString(privatekey);
Cipher cipher=cipher.getInstance("RSA");
cipher.init(cipher.DECRYPT_MODE, key);
byte[] output = cipher.doFinal(input);
return new String(output);
}
2、使用aesKey对加密的业务字段bizData进行解密得到业务数据
public String decryptByAESPadding(String bizData, String aesKey){
byte[] byteData=Base64.decodeBase64(bizData);
byte[] byteAesKey =aesKey.getBytes();
Cipher cipher =Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec keySpec =new SecretKeySpec(byteAesKey,"AES");
cipher.init(cipher.DECRYPT_MODE,keySpec);
byte[l ret =cipher.doFinal(data);
return new String(ret);
}