Java PublicKey对象与base64格式数据转化

Java中要生成PublicKey需要KeyPair对象,先生成KeyPair,通过KeyPairGenerator,这需要结合算法并设置长度,常用的为RSA,长度可以是 1024,2048等。示例如下:

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
assertNotNull(keyPair);

PrivateKey aPrivate = keyPair.getPrivate();
PublicKey aPublic = keyPair.getPublic();

//base64
String base64PrivateKey = new String(Base64.encodeBase64Chunked(aPrivate.getEncoded()));
// System.out.println(base64PrivateKey);
String base64PublicKey = new String(Base64.encodeBase64Chunked(aPublic.getEncoded()));
// System.out.println(base64PublicKey);

使用Base64可将生成的PublicKey,PrivateKey转化为方便传输的 base64格式数据,转化后的PublicKey数据如:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq7h9NrI7OF4m2R53nemmih4N2ds13n/L
ARfFO1hDGKwE36iU+bCLlkw59gPrWgcsc4lKqVrQC3S3NlBIbkX7pcP2zGth3j5uCfM9DOnM+Jxg XyYVDf9YduuevII142BmG/5CGjrdJmDS4wdUZ+vXJPiSGXMdpRM4+p8jcPoZ71YUPJzxu9pOgD37 RL1UdD3wvM63sixPSmmwTua4GExcKnNZzeiM91UqvI90CG+gH/YG0hf2Pnd5ACquToFLPsUn95d6 cqIERTDi8NiBzB/AhlISM69IDnLhRdU8YjZuxoaFZhQT8eZ6Qhr75/aiUu0zN3aNeOHnrJHKV/Lq
xng6VQIDAQAB

当需要使用时可通过 KeyFactory 将base64数据转化为具体的PublicKey或PrivateKey对象。代码如下:

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64PrivateKey));
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
assertNotNull(privateKey);
assertEquals(privateKey, aPrivate);


PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(base64PublicKey)));
assertNotNull(publicKey);
assertEquals(publicKey, aPublic);

转化后的对象与原生的是一样的,可用于加密/解密, 签名验签等。

代码链接:https://gitee.com/mkk/MyOIDC/blob/b14bb9ef6da6ca6235b2f705cbd713fbe97f6436/myoidc-server/src/test/java/myoidc/server/service/business/RSAPublicKeyTest.java

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.