tdgs
tdgs

Reputation: 183

Obtaining public key from SubjectPublicKeyInfo

I'm trying to get the public key from a SubjectPublicKeyInfo.However when I try:

PublicKey publicKey = k.generatePublic(keypsec);

byte[] encoded=publicKey.getEncoded();
SubjectPublicKeyInfo subPkInfo2 = new SubjectPublicKeyInfo(rsaEncryption, encoded);     
RSAPublicKeyStructure  pubKey = new RSAPublicKeyStructure((ASN1Sequence)subPkInfo2.getPublicKey());

It throws this

java.lang.IllegalArgumentException: illegal object in getInstance: org.bouncycastle.asn1.DERSequence
    at org.bouncycastle.asn1.DERInteger.getInstance(DERInteger.java:37)
    at org.bouncycastle.asn1.x509.RSAPublicKeyStructure.<init>(RSAPublicKeyStructure.java:63)

Any ideas? I've tried PubliKeyFactory but it simply calls the last line.

Upvotes: 1

Views: 6081

Answers (1)

tdgs
tdgs

Reputation: 183

Well I shall answer my own question:

byte[] encoded=publicKey.getEncoded();
SubjectPublicKeyInfo subPkInfo2 = new SubjectPublicKeyInfo(rsaEncryption, encoded); 

This is wrong. PublicKey is already an ASN1typeSubjectpublicKeyInfo. In order to create a SubjectPublicKeyInfo with this function

SubjectPublicKeyInfo(AlgorithmIdentifier algId, byte[] publicKey)

you need an Algortihm identifier and THE KEY ITSELF in encoded form. publicKey.getEncoded() is an encoded KEY + THE ALGORITHM IDENTIFIER.

Anyway. If you want to tranfosrm a SATSA public key to a Subject Public Key Info you do this:

byte[] publickeyb=SATSApublickey.getEncoded();
    SubjectPublicKeyInfo subPkInfo = new SubjectPublicKeyInfo((ASN1Sequence)ASN1Object.fromByteArray(publickeyb));

And if you want to get your public key as RSAkeyparameters from the SubjectPublicKeyInfo

RSAKeyParameters param=(RSAKeyParameters) PublicKeyFactory.createKey(subPkInfo);

Upvotes: 5

Related Questions