DES加密解密中的乱码问题

最近在写程序时需要用到加密解密算法,百度了一堆,决定用DES写,DES加密生成字节数组,此数组不管用哪种编码方式进行编码都是生成乱码的字符串,此时需要借助BASE64进行处理,代码如下:
package com.ky.controller.test.md5;

import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

/**
 * @author Luyong
 */
public class DESSecretUtil {

	/**
	 * 使用DES对字符串加密
	 * 
	 * @param str
	 *            utf8编码的字符串
	 * @param key
	 *            密钥(56位,7字节)
	 * 
	 */
	public static byte[] desEncrypt(String str, String key) throws Exception {
		if (str == null || key == null)
			return null;
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "DES"));
		byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
		return bytes;
	}

	/**
	 * 使用DES对数据解密
	 * 
	 * @param bytes
	 *            utf8编码的二进制数据
	 * @param key
	 *            密钥(16字节)
	 * @return 解密结果
	 * @throws Exception
	 */
	public static String desDecrypt(byte[] bytes, String key) throws Exception {
		if (bytes == null || key == null)
			return null;
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "DES"));
		bytes = cipher.doFinal(bytes);
		return new String(bytes, "utf-8");
	}

	/**
	 * 使用base64解决乱码
	 * 
	 * @param secretKey
	 *            加密后的字节码
	 */
	public static String jdkBase64String(byte[] secretKey) {
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(secretKey);
	}

	/**
	 * 使用jdk的base64 解密字符串 返回为null表示解密失败
	 * 
	 * @throws IOException
	 */
	public static byte[] jdkBase64Decoder(String str) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		return decoder.decodeBuffer(str);
	}

	public static void main(String[] args) throws Exception {

		String openId = "sdn_" + jdkBase64String(desEncrypt("DDOS_7", "sdn_ddos"));
		System.out.println(openId);

		String s = openId.replace("sdn_", "");
		String desDecrypt = desDecrypt(jdkBase64Decoder(s), "sdn_ddos");
		System.out.println(desDecrypt);
	}

}
解密失败算我输
  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值