繁体   English   中英

Java cipherinputstream将所有输入数据都设为0

[英]Java cipherinputstream turns all input data to 0

我正在编写一个使用RSA密码和AES密码的公用和专用密钥加密算法的实现。 在这种方法中,应该使用RSA CipherInputStream对AES密钥进行解密。

public void loadKey(File in, byte[] privateKey) throws GeneralSecurityException, IOException {

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pk = kf.generatePrivate(privateKeySpec);
    rsacipher.init(Cipher.DECRYPT_MODE, pk);

    aesKey = new byte[128/8];
    FileInputStream fis = new FileInputStream(in);
    CipherInputStream input = new CipherInputStream(fis, rsacipher);
    input.read(aesKey);
    aesKeySpec = new SecretKeySpec(aesKey, "AES");
    input.close();
    fis.close();
 } 

FileInputStream给了我编码密钥(这不是问题),但是当通过CipherInputStream传递时,数据变为全零。

aesKey和aesKeySpec是静态变量,privateKey是有效的RSA密钥。

任何发现问题的帮助将不胜感激!

从源头CipherInputStreamCipherInputStream可以很好CipherInputStream加密层引发的异常。 我会完全避免使用它来支持简单的Cipher对象,例如

byte[] fileData = FileUtils.readFileToByteArray(in); // from commons-lang
Cipher c = new Cipher("RSA/None/PKCS1Padding");
c.init(Cipher.DECRYPT_MODE, pk);
aesKey = c.doFinal(fileData);
// etc.

您将忽略InputStream.read(byte[])方法的返回值:

input.read(aesKey);

不能保证此调用一次性读取等于传递的字节数组长度的字节数。 您应该使用一个循环,并从输入流中反复读取到数组的其余部分:

int offset = 0;
while (offset < aesKey.length) {
    int read = input.read( aesKey, offset, aesKey.length - offset );
    if (read < 0) {
         throw new EOFException();
    } else {
         offset += read;
    }
}

或者,您可以将流包装到DataInputStream并使用DataInputStream.readFully(byte[])方法(该方法实质上包含与上述相同的代码)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM