package com.hcp.config.rsa;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.Cipher;
import java.security.*;
public class RsaUtil {
/**
* 公钥
*/
private static PublicKey publicKey;
/**
* 私钥
*/
private static PrivateKey privateKey;
/**
* 编码
*/
private static final String CHARSET = "UTF-8";
/**
* 初始化
*/
static void init() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 设置密钥长度
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
}
/**
* 加密
*/
public static String encrypt(String plaintext, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(CHARSET));
return new String(Base64.encode(encryptedBytes), CHARSET);
}
/**
* 解密
*/
public static String decrypt(String ciphertext, PrivateKey privateKey) throws Exception {
byte[] encryptedBytes = Base64.decode(ciphertext.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, CHARSET);
}
public static void main(String[] args) throws Exception {
RsaUtil.init();
String plaintext = "Hello, World!";
String ciphertext = RsaUtil.encrypt(plaintext, RsaUtil.publicKey);
System.out.println(ciphertext);
String decrypt = RsaUtil.decrypt(ciphertext, RsaUtil.privateKey);
System.out.println(decrypt);
}
}