风格颜色 - 切换

抱歉,当前没有风格

查看: 397|回复: 0

Java DES 加密 解密 示例

[复制链接]

20

主题

20

帖子

127

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
127
发表于 2018-1-23 14:49:29 | 显示全部楼层 |阅读模式
[Java] 纯文本查看 复制代码
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]techzero@163.com[/email]
 * @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

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册 新浪微博登陆

本版积分规则