【问题标题】:Java RSA encryption keeps generating output that cannot be decrypted?Java RSA加密不断生成无法解密的输出?
【发布时间】:2014-08-15 01:36:25
【问题描述】:

我正在尽我最大的努力创建一个程序,该程序将生成一个私有/公共 RSA 密钥集并使用它来发送端到端安全的消息。我正在使用 RSA 私钥/公钥对来安全地传输 AES 密钥,该密钥将用于发送消息。

当我使用 1024 位密钥对时,加密的会话密钥为 128 字节。但是尝试使用 RSA 私钥解密它,它抱怨它只能解密 117 个字节或更少。

当我使用 2048 位密钥对时,加密的会话密钥为 256 字节(但必须为 245 或更少)等。

结果总是一样的:我不能来回传递一个有效的密码。 :(

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    SecretKey sessionKey = keyGen.generateKey();

    // Encrypt the session key with the RSA public key
    Cipher rsaCipher = Cipher.getInstance("RSA");
    rsaCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    byte[] encryptedSessionKey = rsaCipher.doFinal(sessionKey.getEncoded());

    // Simulating other end user: Receive encrypted session key,
    // decrypt it using your private key.
    Cipher rsaDecryptCipher = Cipher.getInstance("RSA");
    rsaDecryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    byte[] decryptedSessionKeyBytes = rsaCipher.doFinal(encryptedSessionKey);
    System.out.println("Decrypted session key bytes");
    System.out.println(decryptedSessionKeyBytes);

编辑:看起来生成的密钥有时会被填充,但我不知道如何停止或破坏它。在加密方面我很笨……直到现在我都依赖于 openssl_seal。

【问题讨论】:

  • 小注:直接打印decryptedSessionKeyBytes是不行的,需要先转换成16进制(或者,如果你想快速做点什么,Arrays.toString(byte[])
  • 好点@owlstead,从一开始我就在使用类似(单线)的东西:(new BASE64Encoder()).encode(decryptedSessionKeyBytes)
  • 不要使用sun.misc.* 类。

标签: java encryption cryptography


【解决方案1】:

除了实际解密之外,您正在使用rsaDecryptCipher 进行所有操作。

最好始终指定操作模式和填充模式,例如"RSA/ECB/OAEPWithSHA1AndMGF1Padding" 用于您的 Cipher 实例。

【讨论】:

  • 我期待一个掌纹 :)
  • 我是掌中之王。
猜你喜欢
  • 2012-05-08
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
相关资源
最近更新 更多