这个加密代码有什么问题?

时间:2015-02-11 09:37:56

标签: java encryption cryptography public-key-encryption

我有以下代码生成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();

1 个答案:

答案 0 :(得分:1)

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