简体   繁体   中英

How can I construct a java.security.PublicKey object from a base64 encoded string?

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.

Code for the above answer

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;
}

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.

Try this....

PublicKey getPublicKey(byte[] encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException
{
    KeyFactory factory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encodedKey);
    return factory.generatePublic(encodedKeySpec);
}

Using spongy castle

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;
}

you can try this solution:

add this dependency:

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.61</version>

and use this method:

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);
}

Here's a code snippet:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM