三重DES中的IV在哪里?

Ger*_*dos 2 java encryption 3des tripledes

我使用三重DES加密数据.它工作正常,但我有一个问题.

我在哪里可以看到初始化向量(IV)?

这是使用BASE64Decoder的3des encyption.

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Crypter {

    Cipher ecipher;
    Cipher dcipher;

    Crypter(String as_Phrase)
            throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException {
        this.ecipher = Cipher.getInstance("DESede");
        this.dcipher = Cipher.getInstance("DESede");
        this.ecipher.init(1, getSecretKey(as_Phrase));
        this.dcipher.init(2, getSecretKey(as_Phrase));

    }

    public String encrypt(String as_valueToEncrypt)
            throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, IOException {
        byte[] lbarr_utf8 = as_valueToEncrypt.getBytes("UTF8");
        byte[] lbarr_enc = this.ecipher.doFinal(lbarr_utf8);

        return new BASE64Encoder().encode(lbarr_enc);
    }

    public String decrypt(String as_valueToDecrypt)
            throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, IOException {
        byte[] lbarr_enc = new BASE64Decoder().decodeBuffer(as_valueToDecrypt);

        byte[] lbarr_utf8 = this.dcipher.doFinal(lbarr_enc);

        return new String(lbarr_utf8, "UTF8");
    }

    private SecretKey getSecretKey(String as_Phrase)
            throws UnsupportedEncodingException {
        return new SecretKeySpec(as_Phrase.getBytes("UTF8"), "DESede");
    }
}
Run Code Online (Sandbox Code Playgroud)

Art*_* B. 6

你可以从密码中获得IV:

ecipher.getIV();
Run Code Online (Sandbox Code Playgroud)

问题是IV期间会产生init.由于您init在构造函数中遇到了为不同密文的每次加密使用相同的IV的问题.最好Cipher为每个加密和解密操作单独生成一个新的并初始化它.

你使用DESede实际的密码DESede/ECB/PKCS5Padding.注意,模式是ECB,不使用IV.所以上面的调用返回null.虽然这是默认模式,但不建议这样做.使用DESede/CBC/PKCS5Padding实际使用IV 更安全.

因此,当您在CBC模式下解密时,您需要传递该IV:

dcipher.init(2, new SecretKeySpec(key, "DESede"), new IvParameterSpec(ecipher.getIV()));
Run Code Online (Sandbox Code Playgroud)

为了减少传递IV的负担,你可以在编码之前将IV附加到密文的前面,然后在解密密文之前将其切掉.DES是64位密码,因此您的IV长度为8个字节.