Domanda

Just jumped into security stuff in Java and was trying to use a digital signature. The thing is that I already generated my RSA keys manually and I would like to sign with them. Is that even possible?

This Is the code I wrote where sk is the servers privatekey, pk is the public server key and modulus is the servers module

public static byte[] sign(byte[] message, BigInteger sk, BigInteger pk, BigInteger modulus) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchProviderException{   
    //Initialize signature
    Signature sig = Signature.getInstance("MD5WithRSA");

    //Create public and private keys
    KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
    RSAPrivateKeySpec skey = new RSAPrivateKeySpec(modulus, sk);
    RSAPrivateKey serverPrivateKey = (RSAPrivateKey)fact.generatePrivate(skey);
    RSAPublicKeySpec pkey = new RSAPublicKeySpec(modulus, pk);
    PublicKey serverPublicKey = fact.generatePublic(pkey);

    //We assign the key
    sig.initSign(serverPrivateKey);
    sig.update(message);
    byte[] signatureBytes = sig.sign();

    return signatureBytes;
}

After running it, I got the following error:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: RSA keys must be at least 512 bits long

Do you guys know how could I face this? I tried several ways of producing a Private / Public key out of my BigInteger values and there was no way.

Would apreciate any help/considerations.

È stato utile?

Soluzione

Although the key is too small for practical use, you may still use it for educational purposes. Note that the key is so small that you cannot even use PKCS#1 padding modes, only "raw" RSA encryption (i.e. only the modular exponentiation part of RSA).

The following works perfectly well for the Bouncy Castle provider (where the key is a 64 bit key):

final Provider bc = new BouncyCastleProvider();

// generating the key from modulus & private exponent
KeyFactory rsaFactory = KeyFactory.getInstance("RSA", bc);
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(key.getModulus(), key.getPrivateExponent());
RSAPrivateKey testKey = (RSAPrivateKey) rsaFactory.generatePrivate(spec);

// using it in a raw cipher
Cipher c= Cipher.getInstance("RSA/ECB/NoPadding", bc);
c.init(Cipher.DECRYPT_MODE, testKey);
c.doFinal(new byte[] {(byte) 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top