Auto commit

上级 16c07c66
public class RSA {
private final PublicKey publicKey;
private final PrivateKey privateKey;
/**
* 自定义公钥和私钥
* @param n 公钥和私钥的n
* @param e 公钥的e
* @param d 私钥的d
*/
public RSA(BigInteger n,BigInteger e,BigInteger d){
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(n, e);
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(n, d);
try {
KeyFactory rsa = KeyFactory.getInstance("RSA");
publicKey = rsa.generatePublic(publicKeySpec);
privateKey = rsa.generatePrivate(privateKeySpec);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 指定密钥大小生成公钥和私钥
* @param keySize 密钥大小
*/
public RSA(int keySize){
try {
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
keyGenerator.initialize(keySize);
KeyPair keyPair = keyGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
System.out.println("publicKey = " + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("privateKey = " + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 获取密文
* @param plainText 明文
* @return 密文
*/
public String encode(String plainText){
try {
Cipher cipher = getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取明文
* @param cipherText 密文
* @return 明文
*/
public String decode(String cipherText){
try {
Cipher cipher = getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(bytes);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册