public class RSATokenUtil {
/**
*
* @param token
* @param publicKey
* @return
* @throws Exception
*/
public static byte[] encryptToken(String token, PublicKey publicKey) throws Exception {
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
return encryptCipher.doFinal(token.getBytes());
}
/**
*
* @param encryptedToken
* @param privateKey
* @return
* @throws Exception
*/
public static String decryptToken(byte[] encryptedToken, PrivateKey privateKey) throws Exception {
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = decryptCipher.doFinal(encryptedToken);
return new String(decryptedBytes);
}
/**
* 生成密钥对
* @return
* @throws NoSuchAlgorithmException
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // 常见的密钥长度,可以根据需要调整
return keyGen.generateKeyPair();
}
/**
*
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02X", b));
}
return result.toString();
}
}
封装一个加密token工具类
最新推荐文章于 2024-05-23 17:45:07 发布