![](/img/trans.png)
[英]From String to java.security.PublicKey object gaves me an illegal character
[英]How can I construct a java.security.PublicKey object from a base64 encoded string?
我有一个来自外部源(Android 商店)的 bse64encoded 字符串公钥,我需要使用它来验证签名内容。 如何将字符串转换为 java.security.PublicKey 接口的实例。 如果这有所作为,我将使用 Java 6。
密钥(可能)是使用标准 java lib 生成的,而不是充气城堡(它来自远程团队,所以我不确定)。 他们的示例代码说使用 Security.generatePublicKey(base64EncodedPublicKey); 但是标准 java 中的 Security 对象没有这样的方法。
上面答案的代码
public static PublicKey getKey(String key){
try{
byte[] byteKey = Base64.decode(key.getBytes(), Base64.DEFAULT);
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(X509publicKey);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
好的咧嘴笑......试试这个
试试这个....
PublicKey getPublicKey(byte[] encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException
{
KeyFactory factory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encodedKey);
return factory.generatePublic(encodedKeySpec);
}
使用海绵城堡
public static PublicKey getPublicKeyFromString(String key) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
org.spongycastle.asn1.pkcs.RSAPublicKey pkcs1PublicKey
= org.spongycastle.asn1.pkcs.RSAPublicKey.getInstance(decodeB64(key));
RSAPublicKeySpec keySpec
= new RSAPublicKeySpec(pkcs1PublicKey.getModulus(), pkcs1PublicKey.getPublicExponent());
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
你可以试试这个解决方案:
添加此依赖项:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.61</version>
并使用此方法:
private Key parsePublicKey(String publicKey) throws IOException {
PEMParser pemParser = new PEMParser(new StringReader(publicKey));
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject());
return converter.getPublicKey(publicKeyInfo);
}
这是一个代码片段:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import org.apache.commons.codec.binary.Base64;
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
BigInteger modulus = new BigInteger(1, Base64.decodeBase64(this.stringValue("n")));
BigInteger exponent = new BigInteger(1, Base64.decodeBase64(this.stringValue("e")));
return kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (InvalidKeySpecException var4) {
throw new InvalidPublicKeyException("Invalid public key", var4);
} catch (NoSuchAlgorithmException var5) {
throw new InvalidPublicKeyException("Invalid algorithm to generate key", var5);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.