编辑代码示例以指定DES密钥值

时间:2014-04-04 09:15:49

标签: java security encryption key des

我有一个使用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 DESEncryptionDecryption {

private static Cipher encryptCipher;  
private static Cipher decryptCipher; 
public static void main(String[] args) {  
try {
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");  
SecretKey secretKey = keygenerator.generateKey();  

encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);  
byte[] encryptedData = encryptData("Classified Information!");  

decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);  
decryptData(encryptedData);
}}}

1 个答案:

答案 0 :(得分:1)

请勿使用KeyGenerator,请使用SecretKeyFactory

String desKey = "0123456789abcdef"; // value from user  
byte[] keyBytes = DatatypeConverter.parseHexBinary(desKey);

SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
SecretKey key = factory.generateSecret(new DESKeySpec(keyBytes));

请注意,DES不是安全算法。考虑使用AES或Triple DES(DESede)。


对于DESede:

String desKey = "0123456789abcdef0123456789abcdef0123456789abcdef"; // user value (24 bytes)  
byte[] keyBytes = DatatypeConverter.parseHexBinary(desKey);

SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(keyBytes));

对于AES,只需:

String aesKey = "0123456789abcdef0123456789abcdef"; // user value (16/24/32 bytes)
byte[] keyBytes = DatatypeConverter.parseHexBinary(aesKey);
SecretKey key = new SecretKeySpec(keyBytes, "AES");