java publickey getencoded,如何从base64编码的字符串构造java.security.PublicKey对象?

I have a bse64encoded string Public key from external source (Android Store) and I need to use it to verify signed content. How can I convert the string into an instance of the java.security.PublicKey interface. I am on Java 6 if that makes a difference.

The key is (probably) generated using standard java lib and not bouncy castle (its from a remote team so I am not sure). Their sample code says to use Security.generatePublicKey(base64EncodedPublicKey); but the Security object in standard java has no such method.

解决方案

Ok for grins ... try this

base64 decode the key data to get a byte array (byte[])

Create a new X509EncodedKeySpec using the byte array

Get an instance of KeyFactory using KeyFactory.getInstance("RSA") assuming RSA here

call the method generatePublic(KeySpec) with the X509EncodedKeySpec

Result /should/ be a public key for your usage.

Java中,数字证书通常包含公钥信息,这些信息是以Base64编码的形式存储的字符串。如果你想将这个字符串转换为`PublicKey`对象,可以按照以下步骤操作: 1. 导入所需的库:首先,你需要导入`java.security.cert.X509Certificate`和`java.security.PublicKey`等相关的Java安全包。 ```java import java.security.*; import java.security.cert.X509Certificate; import javax.crypto.Cipher; ``` 2. 解码Base64字符串:使用`Base64.getDecoder()`方法解码证书中的公钥字符串。 ```java String encodedPublicKey = "..."; // 你的Base64编码的公钥字符串 byte[] decodedBytes = Base64.getDecoder().decode(encodedPublicKey); ``` 3. 创建X509Certificate对象:虽然这不是必需的,但有时证书信息可能一起包含在X509Certificate对象中。如果你有证书,可以这样做: ```java X509Certificate certificate = ...; // 如果你有证书实例 byte[] certificateBytes = certificate.getEncoded(); ``` 4. 从证书或解码后的字节数组创建PublicKey对象:你可以使用`CertificateFactory`和`KeySpec`来解析这些字节并获取公钥。 ```java try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); if (certificate != null) { // 使用证书 byte[] certBytes = certificate.getEncoded(); X509Certificate x509Cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes)); PublicKey publicKey = x509Cert.getPublicKey(); } else { // 使用解码后的字节数组 publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decodedBytes)); } } catch (Exception e) { throw new RuntimeException("Failed to parse public key", e); } ``` 现在,`publicKey`变量就包含了从字符串转换得到的`PublicKey`对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值