DES加解密【JAVA后台】

package com.*.*.web.utils;

import java.security.SecureRandom;
import java.util.Scanner;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;


/**
 * <b>类说明:DES</b>
 * <p>
 * <b>详细描述:</b>
 * @since 2015年8月31日 下午17:00:16
 */
public class DESCryptUtil {
	
	private static final String DES = "DES";
	
	public static final String desKey = "9AAB1D2EE004AAC4";

    public static String doEncrypt(String plainMessage, String hexDesKey) throws Exception {
		byte desKey[] = hexDesKey.getBytes();
		byte desPlainMsg[] = plainMessage.getBytes();
		return Base64.encodeBase64URLSafeString(desCrypt(desKey, desPlainMsg, Cipher.ENCRYPT_MODE));
	}
    
    public static String doDecrypt(String hexEncryptMessage, String hexDesKey) throws Exception{
    	if (hexEncryptMessage == null) {
            return null;
    	}
    	
		byte desKey[] = hexDesKey.getBytes();
		byte desPlainMsg[] = Base64.decodeBase64(hexEncryptMessage);
		return new String(desCrypt(desKey, desPlainMsg, Cipher.DECRYPT_MODE));
	}
    
    private static byte[] desCrypt(byte[] desKey, byte[] desPlainMsg, int CipherMode) throws Exception{
    	try {
			SecureRandom sr = new SecureRandom();
			DESKeySpec dks = new DESKeySpec(desKey);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
			javax.crypto.SecretKey key = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(DES);
			cipher.init(CipherMode, key, sr);
			
			return cipher.doFinal(desPlainMsg);
		} catch (Exception e) {
			String message = "";
			if (CipherMode == Cipher.ENCRYPT_MODE) {
				message = "DES\u52A0\u5BC6\u5931\u8D25";
			} else {
				message = "DES\u89E3\u5BC6\u5931\u8D25";
			}
			throw new Exception(message, e);
		}
	}
    
    public static void main(String[] args) throws Exception{
    	DESCryptUtil se=new DESCryptUtil();
    	for (int i = 0; i < 5; i++) {
    		Scanner scanner=new Scanner(System.in);
	        /*
	         * 加密
	         */
	        System.out.println("请输入要加密的内容:");
	        String content = scanner.next();
	        System.out.println("加密后的密文是:"+se.doEncrypt(content, desKey));
	       
	        /*
	         * 解密
	         */
	        System.out.println("请输入要解密的内容:");
	         content = scanner.next();
	        System.out.println("解密后的明文是:"+se.doDecrypt(content, desKey));
		}
    }
}

*交流分享,杜绝私藏。崇尚开源


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值