package com.ant.jdk8.encrypt; import org.apache.commons.io.FileUtils; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.File; import java.io.IOException; import java.security.*; import java.util.Base64; public class JavaApiRSADemo { private static final String KEY_ALGORITHM_RSA = "RSA"; private static final String ENCODING_UTF8 = "UTF-8"; private static final int KEY_SIZE = 2048; public static void main(String[] args) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { String data = "横看成岭侧成峰"; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); String publicKeyBase64Str = Base64.getEncoder().encodeToString(publicKey.getEncoded()); FileUtils.writeStringToFile(new File("D:\\java-api-rsa-public-key.pem"), publicKeyBase64Str, ENCODING_UTF8); PrivateKey privateKey = keyPair.getPrivate(); String privateKeyBase64Str = Base64.getEncoder().encodeToString(privateKey.getEncoded()); FileUtils.writeStringToFile(new File("D:\\java-api-rsa-private-key.pem"), privateKeyBase64Str, ENCODING_UTF8); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytesEncrypted = cipher.doFinal(data.getBytes(ENCODING_UTF8)); System.out.println("加密后的数据:\n"+Base64.getEncoder().encodeToString(bytesEncrypted)); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytesDecrypted = cipher.doFinal(bytesEncrypted); System.out.println("解密后的数据:\n"+new String(bytesDecrypted)); } }
加密后的数据:EUwDvYCQnwfzsu3GhlEjseQyK4W1Ws1bmBuBuvHuHrhHkGZ7OFBK5o4kcLyBYrSSMZVhTqa9ZHN+r7E3dUpCx6lfR6yaIguAcvX/GVEgm5Rmqw5xahoP4La/VdKVvyB8Nf7OD67zjWjy8ycn86c5c6+EmifuKIKfVRXzHLr102LHT1ZLgyxcB0qmOD1PMdx6U0T3Vblgb8dp4RIJTEikQWMUaEuIwVTV233e6n3JDKPpEkNDeHtfxasXSBvWQETg3yWC1AzHjT40fG+nkM7EQGHuGefuT+WDWrcHDY+9Ry/NzqnYoAhm53BtfPFHa0lGxKrdsjuJIxe5LHvmCBv2eg==
生成的公钥(注意与openssl生成的密钥对的格式进行对比):
生成的私钥(注意与openssl生成的密钥对的格式进行对比):
=============================================================================
package com.ant.jdk8.encrypt; import org.apache.commons.io.FileUtils; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class JavaApiRSAUtil { private static final String KEY_ALGORITHM_RSA = "RSA"; private static final String ENCODING_UTF8 = "UTF-8"; public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException { String data = "横看成岭侧成峰"; System.out.println("加密前的数据:"+data); PublicKey publicKey = getPublicKey("D:\\java-api-rsa-public-key.pem"); String encryptedData = encrypt(publicKey, data); PrivateKey privateKey = getPrivateKey("D:\\java-api-rsa-private-key.pem"); decrypt(privateKey, encryptedData); } /** * 从磁盘上的公钥文件生成PublicKey * @param publicKeyPath * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static PublicKey getPublicKey(String publicKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { byte[] bytesPublicKeyBase64 = FileUtils.readFileToByteArray(new File(publicKeyPath)); byte[] bytesPublicKey = Base64.getDecoder().decode(bytesPublicKeyBase64); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytesPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } /** * 从磁盘上的私钥文件生成PrivateKey * @param privateKeyPath * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static PrivateKey getPrivateKey(String privateKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { byte[] bytesPrivateKeyBase64 = FileUtils.readFileToByteArray(new File(privateKeyPath)); byte[] bytesPrivateKey = Base64.getDecoder().decode(bytesPrivateKeyBase64); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytesPrivateKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } /** * 加密数据并Base64编码 * @param publicKey * @param originalData * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws BadPaddingException * @throws IllegalBlockSizeException */ public static String encrypt(PublicKey publicKey, String originalData) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytesEncrypt = cipher.doFinal(originalData.getBytes(ENCODING_UTF8)); String encryptedDataBase64 = Base64.getEncoder().encodeToString(bytesEncrypt); System.out.println("加密后的数据:"+encryptedDataBase64); return encryptedDataBase64; } /** * 解密数据 * @param privateKey * @param encryptedData * @return * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws BadPaddingException * @throws IllegalBlockSizeException */ public static String decrypt(PrivateKey privateKey, String encryptedData) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_RSA); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytesEncrypt = Base64.getDecoder().decode(encryptedData.getBytes(ENCODING_UTF8)); byte[] bytesDecrypt = cipher.doFinal(bytesEncrypt); String originalData = new String(bytesDecrypt); System.out.println("解密后的数据:"+originalData); return originalData; } }