Search code examples
javac++bouncycastlebotan

Java equivalent of C++ Botan function call


I have a C++ code similar to this:

Botan::AutoSeeded_RNG botan_rng;
Botan::RSA_PrivateKey private_key(botan_rng, 2048);
Botan::PK_Signer botan_pss_signer(private_key, botan_rng, "PSSR_Raw(SHA-256,MGF1,32)");

What I would like to do is to implement the same functionality in Java. What I have tried so far is as follows:

    Signature rsa = null;
    try {
        rsa = Signature.getInstance("SHA256withRSAAndMGF1", "BC");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        e.printStackTrace();
    } 

    try {
        rsa.initSign((PrivateKey)privateKey, new SecureRandom());
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

And the privateKey is generated as

KeyPairGenerator kpg = null;
try {
    kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}

kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();

The question is if I am doing it the right way? Or is there something missing in my Java code? Specially regarding that random generator part I am not sure if the Java SecureRandom is doing similar thing as in Botan::AutoSeeded_RNG and also the algorithm I am using in BC not sure if it is the equivalent for PSSR_Raw(SHA-256,MGF1,32)?


Solution

  • I was able to fix the issue using the following algorithm with BC and setting parameter specs as follows:

    Signature signature = Signature.getInstance("RawRSASSA-PSS", "BC");
    PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, KEY_AUTHORIZATION_INIT_SIGN_SALT_SIZE, 
                PSSParameterSpec.DEFAULT.getTrailerField());
    signature.setParameter(pssParameterSpec);
    

    The key point was to use a RAW algorithm to sign the hash. I got the hint from this post RAW signer