Security3DES

public class Security3DES {
	private static final String Algorithm = "DESede"; //定义 加密算法,可用 DES,DESede,Blowfish
	
	/**
	 * @Title: encryptData
	 * @Description: 加密
	 * @param cryptKey 密钥
	 * @param src
	 * @return
	 */
    public static byte[] encryptData(String cryptKey, byte[] src) {
       try {
            //添加新安全算法,如果用JCE就要把它添加进去
            //Security.addProvider(new com.sun.crypto.provider.SunJCE());
           
            SecretKey deskey = new SecretKeySpec(build3DesKey(cryptKey), Algorithm);
            Cipher cip = Cipher.getInstance(Algorithm);
            cip.init(Cipher.ENCRYPT_MODE, deskey);
            return cip.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;
    }
    
    /**
     * @Title: decryptData
     * @Description: 解密
     * @param cryptKey 密钥
     * @param src
     * @return
     */
	public static byte[] decryptData(String cryptKey, byte[] src) {
		try {
			SecretKey deskey = new SecretKeySpec(build3DesKey(cryptKey),Algorithm);

			Cipher cip = Cipher.getInstance(Algorithm);
			cip.init(Cipher.DECRYPT_MODE, deskey);
			return cip.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;
	}
    
	/**
	 * @Title: build3DesKey
	 * @Description: 将key转为24位byte
	 * @param keyStr
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException {
		byte[] key = new byte[24];
		byte[] temp = keyStr.getBytes("UTF-8");
		if (key.length > temp.length) {
			System.arraycopy(temp, 0, key, 0, temp.length);
		} else {
			System.arraycopy(temp, 0, key, 0, key.length);
		}
		return key;
	}
	
    public static void main(String[] args){
		try {
			String keyBytes = "012345678901234567890123";

			String szSrc = "This is a 3DES test. 测试";

			System.out.println("加密前的字符串:" + szSrc);

			byte[] encoded = encryptData(keyBytes, szSrc.getBytes());
			BASE64Encoder enc = new BASE64Encoder();
			String cipherString = enc.encode(encoded);
			System.out.println("加密后的字符串:" + cipherString);

			BASE64Decoder base64 = new BASE64Decoder();

			byte[] byStr = base64.decodeBuffer(cipherString);
			byte[] srcBytes = decryptData(keyBytes, byStr);
			System.out.println("解密后的字符串:" + (new String(srcBytes)));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值