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

加解密

程序员文章站 2022-03-04 15:38:33
...

package com.pingan.main;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

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

/**
 * DES加密介绍 DES是一种对称加密算法,所谓对称加密算法即:加密和解密使用相同密钥的算法。DES加密算法出自IBM的研究,
 * 后来被美国*正式采用,之后开始广泛流传,但是近些年使用越来越少,因为DES使用56位密钥,以现代计算能力,
 * 24小时内即可被破解。虽然如此,在某些简单应用中,我们还是可以使用DES加密算法,本文简单讲解DES的JAVA实现 。
 * 注意:DES加密和解密过程中,密钥长度都必须是8的倍数
 */
public class LoginDesUtil {
	public LoginDesUtil() {
	}

	// 测试
	public static void main(String args[]) throws Exception {
		String plaintext = "that is the New game!";
		System.out.println("URLEncode前:" + plaintext);
		String key = "T0FgyDSM";
		plaintext=URLEncoder.encode(plaintext,"UTF-8");
		String ciphertext = LoginDesUtil.encryptDES(plaintext, key);
		System.out.println("明文:" + plaintext);
		System.out.println("密钥:" + key);
		System.out.println("密文:" + ciphertext);
		System.out.println("解密后:" + LoginDesUtil.decryptDES(ciphertext, key));
		System.out.println("URLEncode后:" + URLDecoder.decode(LoginDesUtil.decryptDES(ciphertext, key),"UTF-8"));
	}

	private static byte[] iv = { 1, 4, 7, 8, 5, 2, 6, 3 };

	public static String encryptDES(String encryptString, String encryptKey)
			throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKey key = generateKey(encryptKey);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
		return Base64.encodeBase64String(encryptedData);
	}

	public static String decryptDES(String decryptString, String decryptKey)
			throws Exception {
		byte[] byteMi = Base64.decodeBase64(decryptString);
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKey key = generateKey(decryptKey);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);

		return new String(decryptedData);
	}
	
	public static SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{  
		KeyGenerator _generator = KeyGenerator.getInstance("DES");  
        //防止linux下 随机生成key   
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
        secureRandom.setSeed(secretKey.getBytes());  
          
        _generator.init(56,secureRandom);  
	      
	    // 生成密钥  
	    return _generator.generateKey();  
	} 
}