Skip to content

Instantly share code, notes, and snippets.

@sl4m
Created January 15, 2012 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sl4m/1617144 to your computer and use it in GitHub Desktop.
Save sl4m/1617144 to your computer and use it in GitHub Desktop.
Create PublicKey object using public key generated from pre-Ruby 1.9.3 and SpongyCastle
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import org.spongycastle.asn1.ASN1InputStream;
import org.spongycastle.asn1.DERObject;
import org.spongycastle.asn1.x509.RSAPublicKeyStructure;
import org.spongycastle.util.encoders.Base64;
public class RSAUtil {
static public PublicKey publicKey(String publicKeyString) {
try {
byte[] decodedPublicKey = Base64.decode(publicKeyString);
ASN1InputStream in = new ASN1InputStream(decodedPublicKey);
DERObject obj = in.readObject();
RSAPublicKeyStructure keyStruct = RSAPublicKeyStructure.getInstance(obj);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(keyStruct.getModulus(), keyStruct.getPublicExponent());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment