欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DES对称加密算法

程序员文章站 2024-03-14 10:36:04
...

前言:

1.DES是一个经典的分组加密算法,以64位为分组对数据进行加密(分组),加密和解密使用的是同一个算法(对称);
2.**长64位,事实上56位参与DES运算,每8位中最后一位是奇偶校验位(保证**每8位都有奇数个1);
3.加密过程:对于每一个明文分组,进行一次初始置换IP(Initial Permutation),之后循环使用16个子**进行16轮加密,最后进行一次末置换(IP^-1)。
 

public class  DesEncrypt {
	private static Logger logger = Logger.getLogger(DesEncrypt.class);
	
    //算法名称 
    public static final String KEY_ALGORITHM = "DES";
    public static final String KEY_KEY = "A1B2C3D4E5F60708";
    //算法名称/加密模式/填充方式 
    //DES共有四种工作模式-->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式
    //public static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";
   public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
    /**
     *   
     * 生成**key对象
     * @param KeyStr **字符串 
     * @return **对象 
     * @throws InvalidKeyException   
     * @throws NoSuchAlgorithmException   
     * @throws InvalidKeySpecException   
     * @throws Exception 
     */
    private static SecretKey keyGenerator(String keyStr) throws Exception {
        byte input[] = HexString2Bytes(keyStr);
        DESKeySpec desKey = new DESKeySpec(input);
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        return securekey;
    }

    private static int parse(char c) {
        if (c >= 'a') return (c - 'a' + 10) & 0x0f;
        if (c >= 'A') return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }

    // 从十六进制字符串到字节数组转换 
    public static byte[] HexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }

    /** 
     * 加密数据
     * @param data 待加密数据
     * @param key **
     * @return 加密后的数据 
     */
    public static String encrypt(String data, String key)  {
        byte[] results = null;
		try {
			Key deskey = keyGenerator(key);
			// 实例化Cipher对象,它用于完成实际的加密操作
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			SecureRandom random = new SecureRandom();
			// 初始化Cipher对象,设置为加密模式
			cipher.init(Cipher.ENCRYPT_MODE, deskey, random);
			results = cipher.doFinal(data.getBytes());
			// 该部分是为了与加解密在线测试网站的十六进制结果进行核对
			for (int i = 0; i < results.length; i++) {
			    System.out.print(results[i] + " ");
			}
			System.out.println();
			// 执行加密操作。加密后的结果通常都会用Base64编码进行传输 
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return Base64.encodeBase64String(results);
    }

    /** 
     * 解密数据 
     * @param data 待解密数据 
     * @param key ** 
     * @return 解密后的数据 
     */
    public static String decrypt(String data, String key)  {
    	byte[]  ret  = null;
    	try {
			Key deskey = keyGenerator(key);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
			//初始化Cipher对象,设置为解密模式
			cipher.init(Cipher.DECRYPT_MODE, deskey);
			// 执行解密操作
			ret	= cipher.doFinal(Base64.decodeBase64(data));
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new String(ret);
    }

  
    
	/**
	 * 批量验证权限
	 * @param request
	 * @param chkParamNames
	 * @return
	 */
	public static boolean checkScrect(HttpServletRequest request,
			String[] chkParamNames) {
		StringBuffer buffer = new StringBuffer();
		for(int i=0;i<chkParamNames.length;i++){
			String param=StringUtils.trimToEmpty(request.getParameter(chkParamNames[i]));
			buffer.append(new String(DesEncrypt.decrypt(param, DesEncrypt.KEY_KEY)));
		}
		String secret=request.getParameter(AppConstant.PARAM_SECRECT);
		String secretD=new String(DesEncrypt.decrypt(secret,DesEncrypt.KEY_KEY ));
	    logger.info("buffer:"+buffer.toString());
		logger.info("secretD:"+secretD);
		if(buffer.toString().equals(secretD)){
			return true;
		}
		return false;
	}
    
	  public static void main(String[] args) throws Exception {
        String source = "哈哈";
        System.out.println("原文: " + source);
        String key = "A1B2C3D4E5F60708";
        String encryptData = encrypt(source, key);
        System.out.println("加密后: " + encryptData);
        String decryptData = decrypt(encryptData, key);
        System.out.println("解密后: " + decryptData);
        
        System.out.println(DesEncrypt.decrypt("Xo5QuTUR/GIMocTHz1FIQIc9+Id22JDj", DesEncrypt.KEY_KEY));
    }
    
}