[英]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密鑰。
任何發現問題的幫助將不勝感激!
從源頭CipherInputStream
, CipherInputStream
可以很好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.