Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Created January 14, 2025 17:48
Show Gist options
  • Save markscottwright/440ed35d688cab86b94b7431376de1ef to your computer and use it in GitHub Desktop.
Save markscottwright/440ed35d688cab86b94b7431376de1ef to your computer and use it in GitHub Desktop.
Given an exponent and modulus, output a PEM encoded public key.
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
public class MakePublicKey {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
var modulus = new BigInteger(args[0], 16);
var exponent = new BigInteger(args[1], 16);
var spec = new RSAPublicKeySpec(modulus, exponent);
var pub = KeyFactory.getInstance("RSA").generatePublic(spec);
System.out.println("-----BEGIN RSA PUBLIC KEY-----");
System.out.println(Base64.getMimeEncoder().encodeToString(pub.getEncoded()));
System.out.println("-----END RSA PUBLIC KEY-----");
}
}
@markscottwright
Copy link
Author

Note that as of java 11, you can run this like java MakePublicKey.java MODULUS EXPONENT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment