【问题标题】:Generating RSA public key from byte array从字节数组生成 RSA 公钥
【发布时间】:2015-05-16 18:37:41
【问题描述】:

我在生成 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,这是我在文件中输入的值。我认为错误可能是我创建密钥的方式。

【问题讨论】:

  • 我想我找到了问题所在。显然 BigInteger(byte[] array) 被解释为二进制补码形式。因此我的模数是负数。

标签: java rsa bouncycastle


【解决方案1】:

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

因此,使用这个构造函数解决了BigInteger(int signum, byte[] array) 的问题。

【讨论】:

  • 对于任何潜在的读者,正数为 1,负数为 -1
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2017-09-24
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多