【问题标题】:password based en/decrypting in java: fails to decrypt the file even though the password is identicaljava中基于密码的加密/解密:即使密码相同也无法解密文件
【发布时间】:2012-06-17 14:18:36
【问题描述】:

我为text file加解密写了如下代码。

加密过程正常,但我无法解密创建的文件。出于某种原因,即使我使用相同的密码,相同的长度和相同的填充,解密输出是一个与原始文件不同的编码文件......

在其他尝试中,我在单独运行中运行加密和解密时失败了。但是现在它们都在一个接一个地运行(即使它们使用不同的密钥规范,这是原因吗?如果是这样 - 我该如何绕过它?)

public static void main(String[] args) throws Exception {
    encrypt("samplePassword", new FileInputStream("file.txt"), new FileOutputStream("enc-file.txt"));
    decrypt("samplePassword", new FileInputStream("enc-file.txt"), new FileOutputStream("file-from-enc.txt"));
}

public static void encrypt(String password, InputStream is, OutputStream os) throws Exception {

    SecretKeySpec keySpec = new SecretKeySpec(password(password), "TripleDES");
    Cipher cipher = Cipher.getInstance("TripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    byte[] buf = new byte[8096];
    os = new CipherOutputStream(os, cipher);
    int numRead = 0;
    while ((numRead = is.read(buf)) >= 0) {
        os.write(buf, 0, numRead);
    }
    os.close();
}

public static void decrypt(String password, InputStream is, OutputStream os) throws Exception {

    SecretKeySpec keySpec = new SecretKeySpec(password(password), "TripleDES");
    Cipher cipher = Cipher.getInstance("TripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);

    byte[] buf = new byte[8096];
    CipherInputStream cis = new CipherInputStream(is, cipher);
    int numRead = 0;
    while ((numRead = cis.read(buf)) >= 0) {
        os.write(buf, 0, numRead);
    }
    cis.close();
    is.close();
    os.close();
}

private static byte[] password(String password) {

    byte[] baseBytes = { (byte) 0x38, (byte) 0x5C, (byte) 0x8, (byte) 0x4C, (byte) 0x75, (byte) 0x77, (byte) 0x5B, (byte) 0x43,
            (byte) 0x1C, (byte) 0x1B, (byte) 0x38, (byte) 0x6A, (byte) 0x5, (byte) 0x0E, (byte) 0x47, (byte) 0x3F, (byte) 0x31,
            (byte) 0xF, (byte) 0xC, (byte) 0x76, (byte) 0x53, (byte) 0x67, (byte) 0x32, (byte) 0x42 };
    byte[] bytes = password.getBytes();
    int i = bytes.length;
    bytes = Arrays.copyOf(bytes, 24);
    if(i < 24){
        for(;i<24; i++){
            bytes[i] = baseBytes[i];
        }
    }
    return bytes;
}

谁能给我一个提示?

【问题讨论】:

  • 你能参考你从哪里得到这个可以链接吗?!

标签: java encryption


【解决方案1】:

乍一看,

cipher.init(Cipher.ENCRYPT_MODE, keySpec);

应该是

cipher.init(Cipher.DECRYPT_MODE, keySpec);

在解密方法中。

看看documentation

【讨论】:

  • 哇...没想到我会做到... 10x!它有效(当然......)
猜你喜欢
  • 2016-10-15
  • 2015-04-21
  • 2011-09-14
  • 1970-01-01
  • 2021-06-21
  • 2023-03-17
  • 2020-11-10
  • 2018-05-22
  • 2021-07-12
相关资源
最近更新 更多