2015-02-11 64 views
1

我有以下生成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

謝謝!在獲取字節數組之前,我調用了cipherOutputStream.close(),並且它現在可以工作。奇怪的是,這段代碼幾周來一直工作正常,沒有刷新卡珀斯輸出流。 – user3573403 2015-02-11 09:54:42

+0

然後你不應該接受我以前的回答:)這是錯誤的,因爲我混淆了「密鑰大小」和「塊大小」兩個術語。不過,似乎解決方案是調用flush方法:) – mkrakhin 2015-02-11 09:58:47