gpt4 book ai didi

java - 在 jce api 中为密码学 java 提供我自己的 key

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:35:03 26 4
gpt4 key购买 nike

我想使用 JCE API 通过 DES 算法加密和解密文件和字符串我想给自己的 key 但是当我寻找一个例子时,我发现 key 是这样生成的:

    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。它允许您使用保存 key 的字节数组。

然后可以将该实例作为 key 传递给 Cipher.init 方法。

关于java - 在 jce api 中为密码学 java 提供我自己的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099604/

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