java rsa加密


生成公钥和私钥

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

使用公钥加密 使用私钥解密(或者使用私钥加密  公钥解密)

// 使用公钥加密
byte[] obj = "你好".getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enbs = cipher.doFinal(obj);


// 使用私钥解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] debs = cipher.doFinal(enbs);

根据私钥的modules 和 privateExponent 还原私钥

// 一个密钥对 公钥和私钥的modules是一摸一样的
BigInteger bigM = new BigInteger("私钥的modules");
BigInteger bigPriE = new BigInteger("私钥的privateExponent");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigM, bigPriE);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

根据公钥的modules 和 publicExponent 还原公钥

BigInteger bigM = new BigInteger("公钥的modules");
BigInteger bigPubE = new BigInteger("公钥的publicExponent");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigM, bigPubE);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);