Java加解密——Base64与DES

一、BASE64

这里选用Java自带的BASE64Encoder和BASE64Decoder进行BASE64编码,除此之外,可以选择commons-codec.jar等第三方jar包进行实现。

BASE64Encoder和BASE64Decoder为实现BASE64的API,为了解决高并发问题,提高运行效率,本例将encoder和decoder作为全局静态属性,并通过ThreadLocal进行管理。


package com.fhp.testencrypt;

import sun.misc.BASE64Encoder;
import java.io.IOException;
import sun.misc.BASE64Decoder;

public class Base64Utils {
	
	private static ThreadLocal<BASE64Encoder> encoder = new ThreadLocal<BASE64Encoder>() {
		@Override
		protected BASE64Encoder initialValue() {
			return new BASE64Encoder();
		}
	};
	
	private static ThreadLocal<BASE64Decoder> decoder = new ThreadLocal<BASE64Decoder>() {
		@Override
		protected BASE64Decoder initialValue() {
			return new BASE64Decoder();
		}
	};
	
	public static String encode(byte[] bytes) {
		return encoder.get().encode(bytes);
	}
	
	public static byte[] decode(String str) {
		try {
			return decoder.get().decodeBuffer(str);
		} catch (IOException e) {
			throw new RuntimeException("Cannot decode string:" + str, e);
		}
	}
}

二、DES

package com.fhp.testencrypt;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class DESUtils {
	
	// 算法名称  
    private static final String KEY_ALGORITHM = "DES";  
    // 算法名称/加密模式/填充方式  
    private static final String CIPHER_ALGORITHM_ECB = "DES/ECB/PKCS5Padding";
    
    private static final Key defaultKey = generateKey();
    
    /**
     * 生成密钥
     */
    public static Key generateKey() {
    	KeyGenerator keyGenerator;
		try {
			keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Unable to generate DES key.", e);
		}
    	keyGenerator.init(56);//这里必须填56
    	SecretKey secretKey = keyGenerator.generateKey();
    	return secretKey;
    }
    
    /**
     * 使用默认密钥对字节数组进行加密,返回加密后的字节数组
     */
    public static byte[] encrypt(byte[] source) {
    	return encrypt(source, null);
    }
    
    /**
     * 使用默认密钥对字节数组进行解密,返回解密后的字节数组
     */
    public static byte[] decrypt(byte[] source) {
    	return decrypt(source, null);
    }
    
    /**
     * 使用指定密钥对字节数组进行加密,返回加密后的字节数组
     */
	public static byte[] encrypt(byte[] source, Key key) {
		try {
			Key currentKey = key == null ? defaultKey : key;
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);
			cipher.init(Cipher.ENCRYPT_MODE, currentKey, new SecureRandom());  
	        return cipher.doFinal(source);  
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Unable to encrypt.", e);
		} catch (NoSuchPaddingException e) {
			throw new RuntimeException("Unable to encrypt.", e);
		} catch (InvalidKeyException e) {
			throw new RuntimeException("Unable to encrypt.", e);
		} catch (IllegalBlockSizeException e) {
			throw new RuntimeException("Unable to encrypt.", e);
		} catch (BadPaddingException e) {
			throw new RuntimeException("Unable to encrypt.", e);
		}  
	}
	
	 /**
     * 使用指定密钥对字节数组进行解密,返回解密后的字节数组
     */
	public static byte[] decrypt(byte[] source, Key key) {
		try {
			Key currentKey = key == null ? defaultKey : key;
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);
			cipher.init(Cipher.DECRYPT_MODE, currentKey, new SecureRandom());  
	        return cipher.doFinal(source);  
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Unable to decrypt.", e);
		} catch (NoSuchPaddingException e) {
			throw new RuntimeException("Unable to decrypt.", e);
		} catch (InvalidKeyException e) {
			throw new RuntimeException("Unable to decrypt.", e);
		} catch (IllegalBlockSizeException e) {
			throw new RuntimeException("Unable to decrypt.", e);
		} catch (BadPaddingException e) {
			throw new RuntimeException("Unable to decrypt.", e);
		}  
	}
	
	public static void main(String[] args) {
		String str = "测试字符串";
		byte[] encrypted = DESUtils.encrypt(str.getBytes());
				
		byte[] decrypted = DESUtils.decrypt(encrypted);
		System.out.println("cipher text:" + new String(encrypted));
		System.out.println("normal text:" + new String(decrypted));
	}
}


 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值