How to generate a self-signed certificate programmatically?

I have an RSA public key (2048 bits) generated by HSM, this key was saved in a file (256 bytes in size) and encoded as DER.

Is it possible to programmatically create a self-signed certificate using the JDK API (without BouncyCastle) starting from this file?

I am stuck with the first step because I am trying to load a key file to create a PublicKey object:

import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.commons.io.IOUtils;

public class Crypto {
public static void main(String[] args) throws Exception {

    byte[] byteArray = IOUtils.toByteArray(new FileInputStream("/tmp/pub.key"));

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(byteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey pub = kf.generatePublic(spec);
    ....
}
}

but I get this exception:

Exception in thread "main" java.security.spec.InvalidKeySpecException: Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys
    at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:289)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:184)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:304)
    at org.alex.Crypto.main(Crypto.java:17)

Is there any way to do this?

0
source share
2 answers

X509EncodedKeySpec ( PKCS # 1 RSA). . PKCS # 8 , ( PKCS # 8, , ).

+1

! = > Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys

PKCS8EncodedKeySpec, , RSAPublicKeySpec X509EncodedKeySpec class

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");

KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
    "12345678", 16), new BigInteger("11", 16));
RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
    "12345678", 16), new BigInteger("12345678",
    16));

RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
0

Source: https://habr.com/ru/post/1652451/


All Articles