下面再来看个公钥加密私钥解密的代码
package com.demo; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import sun.misc.BASE64Encoder; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class rsademo { private static String name = "xiaoming"; public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { // 1.初始化密钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");//设置获取RSA的密钥 keyPairGenerator.initialize(512);//设置密钥长度 KeyPair keyPair = keyPairGenerator.generateKeyPair();//生成密钥对 RSAPublicKey rsaPublic =(RSAPublicKey) keyPair.getPublic();//获取公钥 RSAPrivateKey rsaPrivate = (RSAPrivateKey)keyPair.getPrivate();//获取私钥 // System.out.println(new BASE64Encoder().encode(rsaPublic.getEncoded()));//输出公钥 System.out.println(""); // 3.公钥加密、私钥解密 // 3.1公钥加密 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublic.getEncoded()); KeyFactory encodersa = KeyFactory.getInstance("RSA"); PublicKey publicKey = encodersa.generatePublic(x509EncodedKeySpec); Cipher encodecipher = Cipher.getInstance("RSA"); encodecipher.init(Cipher.ENCRYPT_MODE,publicKey); byte[] encoderes = encodecipher.doFinal(name.getBytes()); System.out.println(new BASE64Encoder().encode(encoderes)); // 3.2私钥解密 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivate.getEncoded()); KeyFactory decodersa = KeyFactory.getInstance("RSA"); PrivateKey privateKey = decodersa.generatePrivate(pkcs8EncodedKeySpec); Cipher decodecipher = Cipher.getInstance("RSA"); decodecipher.init(Cipher.DECRYPT_MODE,privateKey); byte[] decoderes = decodecipher.doFinal(encoderes); System.out.println(new String(decoderes)); } }在代码中其实可以看到用到了x509EncodedKeySpec和pkcs8EncodedKeySpec的类,其实这两个类一个用于对私钥进行编码的,一个是对私钥进行编码。
0x05 结尾