diff --git a/RSA.java b/RSA.java new file mode 100644 index 0000000000000000000000000000000000000000..9d0618694ae3ed5379ff12f5b57122d4a74e14fc --- /dev/null +++ b/RSA.java @@ -0,0 +1,75 @@ +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); + } + } + + + +}