簡體   English   中英

java-從字節數組獲取密鑰

[英]java - get key from byte array

我有一個Java程序,使用隨機生成的密鑰對文件內容進行加密。 該密鑰隨RSA一起加密並保存到文本文件中。

現在,我有一個Java程序,給出了文件和存儲RSA密鑰的密鑰庫,首先需要解密加密的密鑰,然后再使用密鑰解密文件。

這是我到目前為止的內容:

// 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變量?

我以這種方式生成了密鑰:

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)

它可以用於從字節數組構造SecretKey,而不必通過(基於提供程序的)SecretKeyFactory。

此類僅對可以表示為字節數組且沒有與之關聯的密鑰參數(例如DES或Triple DES密鑰)的原始秘密密鑰有用。

如果我做對了,這應該可以工作。

Key privateKey = keyStore.getKey("youralias", "password".toCharArray());
PublicKey publicKey = keyStore.getCertificate("youralias").getPublicKey();

KeyGenerator keyGen = KeyGenerator.getInstance("AES");
Key secKey = keyGen.generateKey();

Cipher keyCipher = Cipher.getInstance("RSA");
keyCipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptedKey = keyCipher.doFinal(secKey.getEncoded());

// Write & Read to/from file!

Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptedKey = decryptCipher.doFinal(encryptedKey);

boolean equals = Arrays.equals(secKey.getEncoded(), new SecretKeySpec(decryptedKey, "AES").getEncoded());
System.out.println(equals?"Successfull!":"Failed!");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM