`
xuelianbobo
  • 浏览: 172218 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

3DES加密解密

 
阅读更多
/*字符串 DESede(3DES) 加密*/
import java.io.IOException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DES3 {

	private static final String Algorithm = "DESede"; // 定义 加密算法,可用

	// DES,DESede,Blowfish
	// keybyte为加密密钥,长度为24字节
	// src为被加密的数据缓冲区(源)
	public static byte[] encryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			// 加密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	// keybyte为加密密钥,长度为24字节 每8个是一组
	// src为加密后的缓冲区
	public static byte[] decryptMode(byte[] keybyte, byte[] src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			// 解密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return c1.doFinal(src);
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	// 转换成十六进制字符串
	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
			if (n < b.length - 1) {
				hs = hs + ":";
			}
		}
		return hs.toUpperCase();
	}

	public static void main(String[] args) throws IOException {
		final byte[] keyBytes = "ceshi123456rewqdsf434368".getBytes(); // 24字节的密钥
		String szSrc = "abcd_123";
		System.out.println("加密前的字符串:" + szSrc);
		byte[] encoded = encryptMode(keyBytes, szSrc.getBytes());
		String encode = new BASE64Encoder().encode(encoded);
		System.out.println("加密后的字符串:" + new String(encode));
		byte[] decodeBuffer = new BASE64Decoder().decodeBuffer("3YV86nsmJEVYa6dW8mIEYA==");
		byte[] srcBytes = decryptMode(keyBytes, decodeBuffer);
		System.out.println("解密后的字符串:" + (new String(srcBytes)));
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics