我正在运行一个来自互联网的java字符串加密/解密类!这是几乎没有修改的类:
公共类EncrypterDecrypter { 密码; Cipher dcipher;
EncrypterDecrypter(SecretKey key)
{
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
}
公共类EncryptionTester {
public static void main(String[] args)
{
try
{
//Generate a temporary key.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
//Create Encrypter/Decrypter class
EncrypterDecrypter crypto = new EncrypterDecrypter(key);
//More lines of code to use crypto object
}
catch (Exception e)
{
}
}
}
我的问题是,每次我创建一个新的EncrypterDecrypter类实例我都会获得不同的加密字符串,但加密的字符串仍然是相同的!我的想法告诉我,问题是SecretKey对象,每次创建一个新实例时都会不断更改,我想知道如何为所有Encrypter / Decrypter类实例使SecretKey对象相同,如果是问题的原因!
答案 0 :(得分:1)
从字节数组生成SecretKey ..
byte raw[] = new byte[]{0x001,0x002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002};
SecretKeySpec spec = new SecretKeySpec(raw, "DES");
答案 1 :(得分:1)
如果您使用javax.crypto
包,则加密和解密方法看起来没问题。
尝试生成你的密钥:
final SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
final SecretKey key = skf.generateSecret(new DESKeySpec(new byte [] {/*The key*/}));
instance.EncrypterDecrypter(key); //Initialization of your Cipher objects
String encrypted = instance.encrypt("This is a test");
System.out.println(instance.decrypt(encrypted)); //"This is a test"
你应该在捕获中做点什么。