トリプル DES
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/** トリプル DES 暗号化/複合化
*/
public final class TripleDesCryptUtilz{
//共通鍵
private static final byte _key = {
(byte)0x01,(byte)0x40,(byte)0xc4,(byte)0x38,(byte)0x67,(byte)0x24,(byte)0x45,(byte)0xf9
,(byte)0xd2,(byte)0x50,(byte)0x58,(byte)0xcf,(byte)0x24,(byte)0x8b,(byte)0xd9,(byte)0x08
,(byte)0x2a,(byte)0x21,(byte)0xb0,(byte)0x68,(byte)0x67,(byte)0xc1,(byte)0x0d,(byte)0x5a
};
//初期ベクトル
private static final byte _iv = {
(byte)0x01,(byte)0x02,(byte)0x03,(byte)0x04,(byte)0x05,(byte)0x06,(byte)0xa0,(byte)0xe7
};
private static final AlgorithmParameterSpec paramSpec = new IvParameterSpec(_iv);
private static final SecretKey _secretKey = new SecretKeySpec(_key,"DESede");
private static final String SCHEME = "DESede/CBC/PKCS5Padding";
private static final String PROVIDER = "SunJCE";
private TripleDesCryptUtilz(){}
/**
* トリプル DES 暗号化→BASE64.
* @param message 対象文字列
* @param charname 対象文字列を暗号化する時に認識する文字コード名、"Shift_JIS" "UTF-8" 等を指定
* @return 暗号化して BASE64 エンコードした文字列
* @throws Exception
*/
public static String encrypt(String message,String charname) throws Exception{
if (message==null || message.length()==0){ return ""; }
Cipher cipher = Cipher.getInstance(SCHEME,PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE,_secretKey,paramSpec);
byte ctext = cipher.doFinal(message.getBytes(charname));
StringBuffer enc = new StringBuffer(new sun.misc.BASE64Encoder().encodeBuffer(ctext));
int point;
while((point=enc.toString().indexOf(System.getProperty("line.separator"))) >= 0){
enc.delete(point,point+System.getProperty("line.separator").length());
}
return enc.toString();
}
public static String encrypt(String message) throws Exception{
return encrypt(message,"Shift_JIS");
}
/**
* トリプル DES 復号化.
* @param message BASE64エンコードしてからトリプルDES 暗号化された文字列
* @param charname 複合後文字コード名、"Shift_JIS" "UTF-8" 等を指定
* @return BASE64デコードしてからでトリプル DES 復号化した文字列
* @throws Exception
*/
public static String decrypt(String message,String charname) throws Exception{
if (message==null || message.length()==0){ return ""; }
Cipher cipher = Cipher.getInstance(SCHEME,PROVIDER);
cipher.init(Cipher.DECRYPT_MODE,_secretKey,paramSpec);
byte ctext = cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(message));
return new String(ctext,charname);
}
public static String decrypt(String message) throws Exception{
return decrypt(message,"Shift_JIS");
}
}