3DES加密、解密示例

import java.io.PrintStream;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Des3Utils {

	public static final String KEY = "aibizhall-biz-zzyyt-1234";

	public static String encryptThreeDESECB(String src) throws Exception {
		DESedeKeySpec dks = new DESedeKeySpec(KEY.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		javax.crypto.SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
		cipher.init(1, securekey);
		byte b[] = cipher.doFinal(src.getBytes());
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(b).replaceAll("\r", "").replaceAll("\n", "");
	}

	public static String decryptThreeDESECB(String src) throws Exception {
		BASE64Decoder decoder = new BASE64Decoder();
		byte bytesrc[] = decoder.decodeBuffer(src);
		DESedeKeySpec dks = new DESedeKeySpec(KEY.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		javax.crypto.SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
		cipher.init(2, securekey);
		byte retByte[] = cipher.doFinal(bytesrc);
		return new String(retByte);
	}

	public static void main(String args[]) throws Exception {
		String a = encryptThreeDESECB(args[0]);
		System.out.println((new StringBuilder()).append("a= ").append(a).toString());
		String b = decryptThreeDESECB(a);
		System.out.println((new StringBuilder()).append("b= ").append(b).toString());
	}
}

你可能感兴趣的:(java)