从字节数组生成RSA公钥

时间:2015-03-14 07:15:05

标签: java rsa bouncycastle

我在生成RSA公钥对象时遇到了一些麻烦。在这种方法中,我将e(指数)和n(模数)从文件读入两个字节数组。我想使用这两个字节数组来创建一个RSA公钥对象。不幸的是,在我的实现中,我得到一个错误,说输入太大而无法加密。但是,e和n都是1024位,输入只有32个字节。

private static void send() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] senderFileBytes = getFileBytes(senderPrivateKeyFile);
    byte[] receiverFileBytes = getFileBytes(receiverPublicKeyFile);
    byte[] plainTextFileBytes = getFileBytes(plainTextFile);
    byte[] senderPrivateKeyBytes = new byte[128];
    byte[] senderModulusBytes = new byte[128];
    byte[] receiverPublicKeyBytes = new byte[128];
    byte[] receiverModulusBytes = new byte[128];

    System.arraycopy(senderFileBytes, 0, senderModulusBytes, 0, 128);
    System.arraycopy(senderFileBytes, 128, senderPrivateKeyBytes, 0, 128);
    System.arraycopy(receiverFileBytes, 0, receiverModulusBytes, 0, 128);
    System.arraycopy(receiverFileBytes, 128, receiverPublicKeyBytes, 0, 128);

    SecureRandom random = new SecureRandom();
    byte[] aesKeyBytes = new byte[16];
    byte[] ivKeyBytes = new byte[16];
    random.nextBytes(aesKeyBytes); //These two are being concatenated 
    random.nextBytes(ivKeyBytes);  //And then encrypted with RSA

    //Relevant section
    BigInteger receiverPublicKeyInteger = new BigInteger(receiverPublicKeyBytes);
    BigInteger receiverModulusInteger = new BigInteger(receiverModulusBytes);
    RSAPublicKeySpec receiverPublicKeySpec = new RSAPublicKeySpec(receiverModulusInteger, receiverPublicKeyInteger);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    RSAPublicKey receiverPublicKey = (RSAPublicKey) keyFactory.generatePublic(receiverPublicKeySpec);

    Cipher rsaCipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
    rsaCipher.init(Cipher.ENCRYPT_MODE, receiverPublicKey);
    byte[] aesIvBytes = concat(aesKeyBytes, ivKeyBytes);
    byte[] sessionCipher = rsaCipher.doFinal(aesIvBytes); //Error here

}

我使用intValue()测试了BigInteger,它们似乎是正确的。例如,receiverPublicKeyInteger的值是65537,这是我在文件中输入的值。我认为错误可能是我创建密钥的方式。

1 个答案:

答案 0 :(得分:1)

解决了这个问题。问题是因为BigInteger(byte[] array)构造函数以两种补码形式读取array。因为模数字节数组不是以两个补码形式解释的,所以使用上面的构造函数可以产生负整数。

因此,使用此构造函数可以解决问题BigInteger(int signum, byte[] array)