【发布时间】:2014-11-28 21:54:32
【问题描述】:
我正在使用三重 DES 加密数据。它工作正常,但我有一个问题。
在哪里可以看到初始化向量 (IV)?
它是带有 BASE64Decoder 的 3des 加密。
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");
}
}
【问题讨论】:
-
您从未想过要查看 Cipher 的 Javadocs?
-
请在上面加糖,如果已定义,请使用常量。如果没有,请定义您自己的,并在新 API 中使用枚举。
Cipher.ENCRYPT_MODE在init方法中比1清晰得多,你不同意吗?
标签: java encryption 3des tripledes