[英]give my own key in jce api for cryptography java
我想使用JCE API通過DES算法對文件和字符串進行加密和解密,並且想提供自己的密鑰,但是當我尋找一個示例時,發現密鑰是這樣生成的:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class JEncrytion
{
public static void main(String[] argv) {
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
String key = "zertyuio";
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
//sensitive information
byte[] text = "No body can see me".getBytes();
System.out.println("Text [Byte Format] : " + text);
System.out.println("Text : " + new String(text));
// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Text Encryted : " + textEncrypted);
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
// Decrypt the text
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Text Decryted : " + new String(textDecrypted));
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(NoSuchPaddingException e){
e.printStackTrace();
}catch(InvalidKeyException e){
e.printStackTrace();
}catch(IllegalBlockSizeException e){
e.printStackTrace();
}catch(BadPaddingException e){
e.printStackTrace();
}
}
}
你有什么主意嗎
先感謝您
看看類javax.crypto.spec.SecretKeySpec
。 它允許您使用保存密鑰的字節數組。
然后可以將該實例作為鍵傳遞給Cipher.init
方法。
對於DES,您可以從DESKeySpec中創建您的密鑰:
SecretKey myDesKey =
SecretKeyFactory.getInstance("DES").generateSecret(new DESKeyspec(key.getBytes()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.