这两天在跟友商对接接口,在对外暴露接口的时候,因为友商不需要登录即可访问对于系统来说存在安全隐患,所以需要友商在调用接口的时候需要将数据加密,系统解密验证后才执行业务。所有的加密方式并不是万能的,只是增加了破解的成本高低而已~~

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom; public class DesEncryptUtils { public static final String KEY = "marklogzhu202306111454"; /**
* 加密
*
* @param content
* 需要加密的内容
* @param password
* 加密密码
* @return
*/
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kgen.init(128, random);
// kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 解密
*
* @param content
* 待解密内容
* @param password
* 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
} /**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
} /**
* 加密
*
* @param content
* 需要加密的内容
* @param password
* 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public static String getDecryptResult(String bizData) throws UnsupportedEncodingException {
byte[] decode = DesEncryptUtils.parseHexStr2Byte(bizData);
byte[] decryptResult = DesEncryptUtils.decrypt(decode, DesEncryptUtils.KEY);
String decryptStr = new String(decryptResult, "UTF-8");
return decryptStr;
} public static void main(String[] args) throws UnsupportedEncodingException {
String content = "hello 中国--2018";
// 加密
System.out.println("加密前:" + content);
byte[] encode = DesEncryptUtils.encrypt(content, DesEncryptUtils.KEY); //传输过程,不转成16进制的字符串,程序就会崩溃掉
String code = DesEncryptUtils.parseByte2HexStr(encode);
System.out.println("密文字符串:" + code);
byte[] decode = DesEncryptUtils.parseHexStr2Byte(code);
// 解密
byte[] decryptResult = DesEncryptUtils.decrypt(decode, DesEncryptUtils.KEY);
System.out.println("解密后:" + new String(decryptResult, "UTF-8")); //不转码会乱码 }
}

启动运行

加密前:hello 中国--2018
密文字符串:3461AA5F7D3434A58C47F4BFBE2AA9D4953E5E3D5717D2EF6ABAD1E421C82B7E
解密后:hello 中国--2018

遇到的问题

现象

在window 环境下加解密都可以,但是 Linux 下解密报空指针异常。

原因

SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264

解决办法

将如下代码替换:

kgen.init(128, new SecureRandom(password.getBytes()));

替换为:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kgen.init(128, random);

DES加解密工具类的更多相关文章

  1. RSA加解密工具类RSAUtils.java,实现公钥加密私钥解密和私钥解密公钥解密

    package com.geostar.gfstack.cas.util; import org.apache.commons.codec.binary.Base64; import javax.cr ...

  2. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

  3. Java中的RSA加解密工具类:RSAUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.utils.log.LogUtils; ...

  4. vue 核心加解密工具类 方法

    1 /* base64 加解密 2 */ 3 export let Base64 = require('js-base64').Base64 4 5 /* md5 加解密 6 */ 7 export ...

  5. Des加解密工具

    import java.security.Key; import java.security.Security; import java.util.Date; import javax.crypto. ...

  6. des 加密解密工具类

    最近在做des的双对称加密解密,特此记录一下. des对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码 ...

  7. 加解密工具类(含keystore导出pfx)

    java代码如下: package sign; import java.io.FileInputStream; import java.io.FileOutputStream; import java ...

  8. C# 加解密工具类

    using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Clov ...

  9. PHP 基础篇 - PHP 中 DES 加解密详解

    一.简介 DES 是对称性加密里面常见一种,全称为 Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法.密钥长度是64位(bit),超过位数密钥被忽略.所谓对 ...

随机推荐

  1. linux初学者-虚拟机联网篇

    linux初学者-虚拟机联网篇 在虚拟机的使用过程中,本机可以连接WIFI直接上网,但是有时候需要用到虚拟机的联网,那么在本机联网的情况下,虚拟机怎么联网呢?接下来将介绍如何在本机已经连接到WIFI的 ...

  2. UPC Contest RankList – 2019年第二阶段我要变强个人训练赛第十六场

    E: 飞碟解除器 •题目描述 wjyyy在玩跑跑卡丁车的时候,获得了一个飞碟解除器,这样他就可以免受飞碟的减速干扰了.飞碟解除器每秒末都会攻击一次飞碟,但每次只有p/q的概率成功攻击飞碟.当飞碟被成功 ...

  3. idea中写servlet时报错--关于405错误

    将super方法注释掉 原因:super是调用了此类继承父类doget和dopost方法的, 如果此类中没有这个方法,就会报错The specified HTTP method is not allo ...

  4. [开源] .NETCore websocket 即时通讯组件---ImCore

    前言 ImCore 是一款 .NETCore 下利用 WebSocket 实现的简易.高性能.集群即时通讯组件,支持点对点通讯.群聊通讯.上线下线事件消息等众多实用性功能. 开源地址:https:// ...

  5. 这半年时间学Mysql的总结

    一条sql语句的执行流程 select * from t where id=1 1.mysql执行一条查询语句的流程 1.1客户端输入用户名密码连接mysql服务器 1.2查询这条sql语句有没有对应 ...

  6. 数字麦克风PDM信号采集与STM32 I2S接口应用

    数字麦克风采用MEMS技术,将声波信号转换为数字采样信号,由单芯片实现采样量化编码,一般而言数字麦克风的输出有PDM麦克风和PCM麦克风,由于PDM麦克风结构.工艺简单而大量应用,在使用中要注意这二者 ...

  7. 证明线程池ThreadPoolExecutor的核心线程数,最大线程数,队列长度的关系

    关于线程池的几个参数,很多人不是很清楚如何配置,他们之间是什么关系,我用代码来证明一下. package www.itbac.com; import java.util.concurrent.*; p ...

  8. Android 属性动画实战

    什么是属性动画? 属性动画可以通过直接更改 View 的属性来实现 View 动画.例如: 通过不断的更改 View 的坐标来实现让 View 移动的效果: 通过不断的更改 View 的背景来实现让 ...

  9. Redis批量删除key的小技巧,你知道吗?

    在使用redis的过程中,经常会遇到要批量删除某种规则的key,但是redis提供了批量查询一类key的命令keys或scan,没有提供批量删除某种规则key的命令,怎么办?看完本文即可,哈哈. 本文 ...

  10. [译]使用golang每分钟处理百万请求

    [译]使用golang每分钟处理百万请求 在Malwarebytes,我们正在经历惊人的增长,自从我在1年前加入硅谷的这家公司以来,我的主要职责是为多个系统做架构和开发,为这家安全公司的快速发展以及百 ...