gpt4 book ai didi

java - 从字节数组中获取 key

转载 作者:行者123 更新时间:2023-12-01 14:59:22 25 4
gpt4 key购买 nike

我有一个java程序,它使用随机生成的 key 加密文件内容。该 key 使用 RSA 加密并保存到文本文件中。

现在,我有一个 java 程序,给定文件和存储 RSA key 的 keystore ,需要首先解密加密的 key ,然后使用该 key 解密文件。

这是我到目前为止所拥有的:

// Fetch the other public key and decrypt the file encryption key
java.security.cert.Certificate cert2 = keystore.getCertificate("keyForSeckeyDecrypt");
Key secKeyPublicKey = cert2.getPublicKey();
Cipher cipher = Cipher.getInstance(secKeyPublicKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secKeyPublicKey);
keyFileFis = new FileInputStream(keyFile);
byte[] encryptedKey = new byte[128];
keyFileFis.read(encryptedKey);
byte[] realFileKey = cipher.doFinal(encryptedKey, 0, encryptedKey.length);
Key realKey = // THE PROBLEM!!!;
keyFileFis.close();

简而言之,我从 key 文本文件中获取加密的 key 并解密它,现在我将解密的 key 作为字节数组,我如何再次将其设为 Key 变量?

我通过这种方式生成了 key :

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
Key secKey = keyGen.generateKey();
cipher.init(Cipher.ENCRYPT_MODE, secKey);

并以这种方式加密:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
PrivateKey privateKey = kp.getPrivate();
Cipher keyCipher = Cipher.getInstance("RSA");
keyCipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptedKey = keyCipher.doFinal(secKey.getEncoded());
FileOutputStream keyStream = new FileOutputStream("key.txt");
keyStream.write(encryptedKey);
keyStream.close();

最佳答案

我还没有尝试过,但通过点击 API SecretKeySpec可能就是您正在寻找的。

SecretKeySpec(byte[] key, String algorithm)

It can be used to construct a SecretKey from a byte array, without having to go through a (provider-based) SecretKeyFactory.

This class is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.

关于java - 从字节数组中获取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13896007/

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