0

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;
}

谁能给我一个提示?

4

1 回答 1

1

乍一看,

cipher.init(Cipher.ENCRYPT_MODE, keySpec);

应该是

cipher.init(Cipher.DECRYPT_MODE, keySpec);

在解密方法中。

看看文档

于 2012-06-17T14:54:43.807 回答