【问题标题】:String Encryption/Decryption class that produces different output产生不同输出的字符串加密/解密类
【发布时间】:2012-02-27 15:25:17
【问题描述】:

我正在运行一个从 Internet 获得的 java 字符串加密/解密类!这是几乎没有修改的类:

公共类 EncrypterDecrypter { 密码密码; 密码密码;

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 对象相同,如果那是问题的原因!

【问题讨论】:

  • 要发布的相关代码将是初始化EncrypterDecrypter 对象的行。 key 你在传递什么?
  • 你说得对,我已经修改了代码!我正在传递一个 DES 密钥算法!

标签: java encryption


【解决方案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"

你应该做点什么。

【讨论】:

  • DESKeySpec 在哪个包中?
  • 发现于:javax.crypto.spec
  • 关键是什么?钥匙的大小应该有限制吗?谢谢
  • 我上次看 DES 是 8 年前的大学 :) 我相信密钥是 56 位,因此是 7 个字节。我不是这个领域的专家,所以这可能是 100% 错误的。无论如何,看起来 DESKeySpec 至少需要 8 个字节,并且字节 8 到 [...] 似乎不会影响加密消息。
【解决方案2】:

从字节数组生成 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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多