I'm attempting to make an application that uses a modulus and exponent to generate a public key for RSA. However, there is the issue that the modulus and exponent are both possibly hex values. This is the code that I have for generating the key, the line marked with the -<--- is where the error is occuring.
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(1,hexToByte(rsaJSON.publickey_exp)),new BigInteger(1,hexToByte(rsaJSON.publickey_mod)));
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pub = factory.generatePublic(spec); <---
Cipher cipher = cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, pub);
.....
String HEXES = "0123456789ABCDEF";
public static String byteToHex( byte [] raw ) {
if ( raw == null ) {
return null;
}
final StringBuilder hex = new StringBuilder( 2 * raw.length );
for ( final byte b : raw ) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
public static byte[] hexToByte( String hexString){
int len = hexString.length();
byte[] ba = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
ba[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
}
return ba;
}
An example modulus and exponent that would be put into this are as follows:
modulus:"B31F9097CA38B4548D7300A0768F262C58D92B190355E382DACA4B79DA52226758FD8EB23CE29F404433411AC90308BEEED093BA157E03982E587496A15BB47A371C32C6B665FF75D6E900CF28CF679E871FB06FF0E90431E829DBE8EBDF7D5024A2D32F8B0D50C0D592E5D31046DE275F81B106088EBECA434493458DBF2B804BC46EC973E8F47408CC454F03F24933A5B100001B47239B44A52CF6A40670CED35060EB84BD6D0829DF8EC84EC49D784CA8583F353086071604DB2F43FA243A05F031033FFB179D8CB281A814B01F8CCC2EC29196BB136905104E23832FA923185743E18924C4E9772ED094D98643C677DE99EF1E598452728A7AC3DF5A1AB9"
exponent:"010001"
The stack trace, for the most part:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: RSA keys must be at least 512 bits long
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(Unknown Source)
at java.security.KeyFactory.generatePublic(Unknown Source)
.....
I'm not going to pretend that I know why this error is happening because my knowledge with RSA encryption is somewhat limited. If anyone could help me figure out why this error keeps cropping up, it would be extremely helpful :)