From 7733c45a38efd463e24573faecd9a7478aca9e7e Mon Sep 17 00:00:00 2001 From: 64586190168b7e02f64e79c2 <64586190168b7e02f64e79c2@devide> Date: Tue, 9 May 2023 10:52:36 +0000 Subject: [PATCH] Auto commit --- RSA.java | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 RSA.java diff --git a/RSA.java b/RSA.java new file mode 100644 index 0000000..9d06186 --- /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); + } + } + + + +} -- GitLab