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

Java DES 加密 解密 示例

程序员文章站 2024-03-13 23:00:28
...

代码:

package com.techzero.des;

import java.security.SecureRandom;

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

/**
 * DESTest.java
 * 
 * @author Techzero
 * @Email [email protected]
 * @Time 2013-12-12 下午2:22:58
 */
public class DESTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String content = "DESTest";
		// 密码长度必须是8的倍数
		String password = "12345678";
		System.out.println("密 钥:" + password);
		System.out.println("加密前:" + content);
		byte[] result = encrypt(content, password);
		System.out.println("加密后:" + new String(result));
		String decryResult = decrypt(result, password);
		System.out.println("解密后:" + decryResult);
	}

	/**
	 * 加密
	 * 
	 * @param content
	 *            待加密内容
	 * @param key
	 *            加密的**
	 * @return
	 */
	public static byte[] encrypt(String content, String key) {
		try {
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			byte[] result = cipher.doFinal(content.getBytes());
			return result;
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param key
	 *            解密的**
	 * @return
	 */
	public static String decrypt(byte[] content, String key) {
		try {
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, securekey, random);
			byte[] result = cipher.doFinal(content);
			return new String(result);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}
}


运行结果:

密 钥:12345678
加密前:DESTest
加密后:��d��{�
解密后:DESTest