【问题标题】:What's wrong with this encryption code?这个加密代码有什么问题?
【发布时间】:2015-02-11 09:37:56
【问题描述】:

我有以下代码生成 AES-128 一次性密钥。之后,我使用从证书中读取的 RSA 公钥加密这个一次性密钥。加密后的字节总是 0。为什么?

    // Generate a one-time key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    SecretKey oneTimeKey = keyGenerator.generateKey();
    System.out.println("Encrypted bytes length: " + oneTimeKey.getEncoded().length); // prints "Plain bytes length: 16"

    // Retrieve public key from certificate
    FileInputStream fileInputStream = new FileInputStream("D:\\test.cer");
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) factory.generateCertificate(fileInputStream);
    PublicKey publicKey = certificate.getPublicKey();

    // Encrypt one-time key using the public key.
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, cipher);
    cipherOutputStream.write(oneTimeKey.getEncoded(), 0, oneTimeKey.getEncoded().length);

    // Retrieve the encrypted bytes.
    System.out.println("Encrypted bytes length: " + byteArrayOutputStream.toByteArray().length); // prints "Encrypted bytes length: 0"
    cipherOutputStream.close();

【问题讨论】:

    标签: java encryption cryptography public-key-encryption


    【解决方案1】:

    在获取字节数组之前尝试刷新密码输出流。

    【讨论】:

    • 谢谢!在获取字节数组之前,我调用了 cipherOutputStream.close(),它现在可以工作了。奇怪的是,这段代码已经运行了好几个星期而没有刷新 ciper 输出流。
    • 那么你不应该接受我之前的回答 :) 这是错误的,因为我混淆了“密钥大小”和“块大小”这两个术语。不过,似乎解决方案是调用flush方法:)
    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 2014-08-29
    • 2013-06-05
    • 2014-06-04
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多