我正在尝试在javacard中加载私钥(在外部应用程序中使用RSA生成)。我写了一些普通的java代码来生成密钥对并打印私钥的指数和模数:
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair kp = keyGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
BigInteger modulus = privateKey.getModulus();
BigInteger exponent = privateKey.getPrivateExponent();
System.out.println(Arrays.toString(modulus.toByteArray()));
System.out.println(Arrays.toString(exponent.toByteArray()));
}
}
然后我将字节数组复制到javacard代码
try {
RSAPrivateKey rsaPrivate = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE, KeyBuilder.LENGTH_RSA_512, false);
byte[] exponent = new byte[]{113, 63, 80, -115, 103, 13, -90, 75, 85, -31, 83, 84, -15, -8, -73, -68, -67, -27, -114, 48, -103, -10, 27, -77, -27, 70, 61, 102, 17, 36, 0, -112, -10, 111, 40, -117, 116, -120, 76, 35, 54, -109, 115, 70, -11, 118, 92, -43, -15, -38, -67, 112, -13, -115, 7, 65, -41, 89, 127, 62, -48, -66, 8, 17};
byte[] modulus = new byte[]{0, -92, -30, 28, -59, 41, -57, 95, -61, 2, -50, -67, 0, 6, 67, -13, 22, 61, -96, -15, -95, 20, -86, 113, -31, -91, -92, 77, 124, 26, -67, -24, 40, -42, -41, 115, -66, 109, -115, -111, -6, 33, -51, 63, -72, 113, -36, 22, 99, 116, 18, 108, 106, 97, 95, -69, -118, 49, 9, 83, 67, -43, 50, -36, -55};
rsaPrivate.setExponent(exponent, (short) 0, (short) exponent.length);
rsaPrivate.setModulus(modulus, (short) 0, (short) modulus.length);
}
catch (Exception e) {
short reason = 0x88;
if (e instanceof CryptoException)
reason = ((CryptoException)e).getReason();
ISOException.throwIt(reason);
}
现在由于某种原因,在设置模数时会抛出CryptoException
,理由为1.根据API,这意味着CryptoException.ILLEGAL_VALUE if the input modulus data length is inconsistent with the implementation or if input data decryption is required and fails.
我真的不知道为什么会失败。在此项目中,无法在卡上生成密钥。
我知道512位不再安全,它仅用于测试目的。它最终将被2048位替换。
答案 0 :(得分:3)
我发现RSAPrivateKey api需要无符号值,BigInteger的toByteArray返回签名版本。这篇文章(BigInteger to byte[])帮我解决了我可以简单地删除模数字节数组中的前导零字节。它现在正常工作。