gpt4 book ai didi

java - 序列化对象解密(和其他字节字段)期间出现 StreamCorruptedException

转载 作者:行者123 更新时间:2023-12-01 09:06:51 26 4
gpt4 key购买 nike

我的软件在解密过程中引发了 StreamCorruptedException:我的密码是AES/CBC/PKCS5Padding,我的 key 是通过PBKey Derivation方法获得的,所以我需要创建一个盐来生成AES128 key 。

我的目标是获得以这种方式形成的文件:

(我将删除异常管理代码以提高可读性)我的密码:

char[] password = passwordString.toCharArray();

SecureRandom random = new SecureRandom();
byte salt[] = new byte[SALT_BYTES];
random.nextBytes(salt);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION, AES_KEY_BITS);

SecretKey tmp = factory.generateSecret(keySpec);

SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

FileOutputStream fout = null;
ObjectOutputStream objOut = null;


fout = new FileOutputStream(PRIVATE_RING_FILENAME);

fout.write(salt);

byte[] ivN = cipher.getIV();
fout.write(ivN);

CipherOutputStream cos = new CipherOutputStream(fout, cipher);
objOut = new ObjectOutputStream(cos);

PrivateKeyRing prvKeyRing = new PrivateKeyRing();
SealedObject sealedObject = new SealedObject(prvKeyRing, cipher);
objOut.writeObject(sealedObject);

fout.close();
objOut.close();
cos.close();

并且它工作没有问题。

我的解密代码:

char[] password = passwordString.toCharArray();

File file = new File(PRIVATE_RING_FILENAME);
FileInputStream fin = new FileInputStream(file);


Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");


byte[] salt = new byte[SALT_BYTES];

fin.read(salt);


SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");


KeySpec keySpec = new PBEKeySpec(password, salt, ITERATION, AES_KEY_BITS);

SecretKey = factory.generateSecret(keySpec);

SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");


byte[] ivN = new byte[AES_BYTES];
fin.read(ivN, 0, AES_BYTES);

cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(ivN));

CipherInputStream cis = new CipherInputStream(fin, cipher);
ObjectInputStream objIn;
PrivateKeyRing prvKeyRing = null;
SealedObject sealedObject = null;
objIn = new ObjectInputStream(cis);

sealedObject = (SealedObject) objIn.readObject();
prvKeyRing = (PrivateKeyRing) sealedObject.getObject(cipher);

objIn.close();
fin.close();
cis.close();

但系统执行时出现 StreamCorruptedException: invalid stream header: 73720019:

objIn = new ObjectInputStream(cis);

如果我尝试在不加密所有作品的情况下编写对象。你有什么想法?当您尝试编写多个序列化对象时,我读到了一些问题,但我认为情况并非如此。

最佳答案

这是因为您使用相同的密码加密和解密两次。该对象首先用密码密封,然后写入密码输出流,其中密码处于密封对象后的状态。这不会产生可以使用初始状态的密码解密的文件。您必须先解封对象,然后从流中读取它,这是不可能的。摆脱密码流或密封对象。

关于java - 序列化对象解密(和其他字节字段)期间出现 StreamCorruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com