import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Random; public class EncryptUtil { public static String MD5Purity(String plainText) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
plainText = buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return plainText.toLowerCase();
} public static int GetRandom(int max, int min) {
Random random = new Random();
int s = random.nextInt(max) % (max - min + 1) + min;
return s;
} public static String aesEncrypt(String str, String key) throws Exception {
if (str == null || key == null) {
return null;
}
str = ZipUtils.gzip(str);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
return Base64.getEncoder().encodeToString(bytes);
} public static String aesDecrypt(String str, String key) throws Exception {
if (str == null || key == null) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = Base64.getDecoder().decode(str);
bytes = cipher.doFinal(bytes);
return ZipUtils.gunzip(new String(bytes, "utf-8"));
} public static String MwEncrypt(String shopguid, String token, String seed, String data) throws Exception {
int start = GetRandom(9, 3);
int end = GetRandom(9, 3);
String keyseed = shopguid + token + seed.substring(start * end, start * end + end);
String key = EncryptUtil.MD5Purity(keyseed);
String encry = EncryptUtil.aesEncrypt(System.currentTimeMillis() + data, key);
if (encry.indexOf("==") == encry.length() - 2) {
encry = "2" + encry.substring(0, encry.indexOf("=="));
;
} else if (encry.indexOf("=") == encry.length() - 1) {
encry = "1" + encry.substring(0, encry.indexOf("="));
} else {
encry = "a" + encry;
}
String autograph = EncryptUtil.MD5Purity(encry);
autograph = start + autograph + end;
encry = autograph.toUpperCase() + encry;
return encry;
} public static String MwEncryptaut(String shopguid, String token, String seed, String data) throws Exception {
int start = GetRandom(9, 3);
int end = GetRandom(9, 3);
System.out.println("start = [" + start + "], end = [" + end + "]");
String keyseed = shopguid + token + seed.substring(start * end, start * end + end);
String key = EncryptUtil.MD5Purity(keyseed);
String encry = ZipUtils.gzip(System.currentTimeMillis() + data);
// EncryptUtil.aesEncrypt(System.currentTimeMillis()+data, key);
if (encry.indexOf("==") == encry.length() - 2) {
encry = "2" + encry.substring(0, encry.indexOf("=="));
;
} else if (encry.indexOf("=") == encry.length() - 1) {
encry = "1" + encry.substring(0, encry.indexOf("="));
} else {
encry = "a" + encry;
}
String autograph = EncryptUtil.MD5Purity(encry + key);
autograph = start + autograph + end;
encry = autograph.toUpperCase() + encry;
return encry;
}
public static String MwDecryptaut(String shopguid, String token, String seed, String data) throws Exception {
//System.out.println("body_str:"+data);
if (data.length() < 35) {
throw new Exception("601");
}
String autograph = data.substring(0, 34);
int start = Integer.parseInt(autograph.substring(0, 1));
int end = Integer.parseInt(autograph.substring(33, 34));
//System.out.println("start:"+start+":::end:"+end);
String keyseed = shopguid + token + seed.substring(start * end, start * end + end);
String key = EncryptUtil.MD5Purity(keyseed);
autograph = autograph.substring(1, 33);
data = data.substring(34, data.length());
String autograph_ne = EncryptUtil.MD5Purity(data + key).toUpperCase();
if (!autograph_ne.equals(autograph)) {
throw new Exception("602");
}
String vl = data.substring(0, 1);
data = data.substring(1, data.length());
if (vl.equals("2")) {
data = data + "==";
} else if (vl.equals("1")) {
data = data + "=";
}
String Decryptstr = ZipUtils.gunzip(data);
long stl = Long.parseLong(Decryptstr.substring(0, 13));
long ltl = System.currentTimeMillis();
long lp = (ltl - stl) / (1000 * 60); if (Math.abs(lp) > 10) {
throw new Exception("603");
}
Decryptstr = Decryptstr.substring(13, Decryptstr.length());
return Decryptstr;
}
public static void main(String[] args) throws Exception {
String str = MwEncryptaut("0001", "0c5f6f217aabb2ea742b0944cd5020f3", "yW2we6Vqf73Qd3pg4mE209949t968lB6957n981i3LtQezfF9z0LDi08d9Li2c52X8h7v5MY3l7000537foITmq49yie8a71lM40", "1");
System.out.println(str);
String destr= MwDecryptaut("0001", "0c5f6f217aabb2ea742b0944cd5020f3", "yW2we6Vqf73Qd3pg4mE209949t968lB6957n981i3LtQezfF9z0LDi08d9Li2c52X8h7v5MY3l7000537foITmq49yie8a71lM40",str );
System.out.println(destr);
}
*/
public static String MwDecrypt(String shopguid, String token, String seed, String data) throws Exception {
if (data.length() < 35) {
throw new Exception("601");
}
String autograph = data.substring(0, 34);
int start = Integer.parseInt(autograph.substring(0, 1));
int end = Integer.parseInt(autograph.substring(33, 34));
//System.out.println("start:"+start+":::end:"+end);
autograph = autograph.substring(1, 33);
data = data.substring(34, data.length());
String autograph_ne = EncryptUtil.MD5Purity(data).toUpperCase();
if (!autograph_ne.equals(autograph)) {
throw new Exception("602");
}
String vl = data.substring(0, 1);
data = data.substring(1, data.length());
if (vl.equals("2")) {
data = data + "==";
} else if (vl.equals("1")) {
data = data + "=";
}
//System.out.println("data:"+data);
//System.out.println("seed:"+seed);
String keyseed = shopguid + token + seed.substring(start * end, start * end + end);
String key = EncryptUtil.MD5Purity(keyseed);
//System.out.println("key:"+key);
String Decryptstr = EncryptUtil.aesDecrypt(data, key);
long stl = Long.parseLong(Decryptstr.substring(0, 13));
long ltl = System.currentTimeMillis();
long lp = (ltl - stl) / (1000 * 60);
if (Math.abs(lp) > 10) {
throw new Exception("603");
}
Decryptstr = Decryptstr.substring(13, Decryptstr.length());
return Decryptstr;
} public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
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 (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
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");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(content);
return result; // ����
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} 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();
} 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;
} /*****************************************************************************************************************/ private static String encryptAes(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
} catch (Exception e) {
System.out.println(e.toString());
}
return replaceSpecial(Base64.getEncoder().encodeToString(crypted));
} public static String replaceSpecial(String s) {
s = s.replaceAll("=", "-Z");
s = s.replaceAll("\\+", "Y-B");
s = s.replaceAll("/", "X-C");
return s;
} public static String encrypt(String data) {
String key = "!@#$won9)6*^43^2";
return encryptAes(data, key);
} public static String encryptPassword(String password) {
if (password.isEmpty()) {
return "";
}
String val = password + "cardmwee";
MessageDigest sh1 = null;
try {
sh1 = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
sh1.update(val.getBytes());
byte[] m = sh1.digest();
return byte2hex(m);
} public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs;
} public static String sha1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString(); } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
package mpos.api.cloud.crypt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.*; public class ZipUtils { public static String gzip(String primStr) {
if (primStr == null || primStr.length() == 0) {
return primStr;
} ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out); gzip.write(primStr.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} // return new sun.misc.BASE64Encoder().encode(out.toByteArray()); return Base64.getEncoder().encodeToString(out.toByteArray());
} public static String gunzip(String compressedStr) {
if (compressedStr == null) {
return null;
} ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try {
// compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
compressed = Base64.getDecoder().decode(compressedStr);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in); byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
} decompressed = out.toString("UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
} return decompressed;
} public static final String zip(String str) {
if (str == null) {
return null;
}
byte[] compressed;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null;
String compressedStr = null;
try {
out = new ByteArrayOutputStream();
zout = new ZipOutputStream(out);
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes("UTF-8"));
zout.closeEntry();
compressed = out.toByteArray();
// compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
compressedStr = Base64.getEncoder().encodeToString(compressed);
} catch (IOException e) {
compressed = null;
} finally {
if (zout != null) {
try {
zout.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return compressedStr;
} public static final String unzip(String compressedStr) {
if (compressedStr == null) {
return null;
} ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
ZipInputStream zin = null;
String decompressed = null;
try {
// byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
byte[] compressed = Base64.getDecoder().decode(compressedStr);
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(compressed);
zin = new ZipInputStream(in);
zin.getNextEntry();
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = zin.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString("UTF-8");
} catch (IOException e) {
decompressed = null;
} finally {
if (zin != null) {
try {
zin.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
}

java 加解密的更多相关文章

  1. Java 加解密技术系列文章

    Java 加解密技术系列之 总结 Java 加解密技术系列之 DH Java 加解密技术系列之 RSA Java 加解密技术系列之 PBE Java 加解密技术系列之 AES Java 加解密技术系列 ...

  2. 160829、Java加解密与数字签名

    ** Java加解密 ** 实现方式:JDK实现,CC,BC JDK提供比较基础的底层的实现:CC提供一些简化的操作:BC提供补充 一.Base64加密 非常简单,加密解密就一个函数. 代码如下: 二 ...

  3. Java加解密与数字签名

    ** Java加解密 ** 实现方式:JDK实现,CC,BC JDK提供比较基础的底层的实现:CC提供一些简化的操作:BC提供补充 一.Base64加密 非常简单,加密解密就一个函数. 代码如下: 二 ...

  4. 11.Java 加解密技术系列之 总结

    Java 加解密技术系列之 总结 序 背景 分类 常用算法 原理 关于代码 结束语 序 上一篇文章中简单的介绍了第二种非对称加密算法 — — DH,这种算法也经常被叫做密钥交换协议,它主要是针对密钥的 ...

  5. 10.Java 加解密技术系列之 DH

    Java 加解密技术系列之 DH 序 概念 原理 代码实现 结果 结束语 序 上一篇文章中简单的介绍了一种非对称加密算法 — — RSA,今天这篇文章,继续介绍另一种非对称加密算法 — — DH.当然 ...

  6. 9.Java 加解密技术系列之 RSA

    Java 加解密技术系列之 RSA 序 概念 工作流程 RSA 代码实现 加解密结果 结束语 序 距 离上一次写博客感觉已经很长时间了,先吐槽一下,这个月以来,公司一直在加班,又是发版.上线,又是新项 ...

  7. 8.Java 加解密技术系列之 PBE

    Java 加解密技术系列之 PBE 序 概念 原理 代码实现 结束语 序 前 边的几篇文章,已经讲了几个对称加密的算法了,今天这篇文章再介绍最后一种对称加密算法 — — PBE,这种加密算法,对我的认 ...

  8. 7.java 加解密技术系列之 AES

    java 加解密技术系列之 AES 序 概念 原理 应用 代码实现 结束语 序 这篇文章继续介绍对称加密算法,至于今天的主角,不用说,也是个厉害的角色 — — AES.AES 的出现,就是为了来替代原 ...

  9. 6. Java 加解密技术系列之 3DES

    Java 加解密技术系列之 3DES 序 背景 概念 原理 代码实现 结束语 序 上一篇文章讲的是对称加密算法 — — DES,这篇文章打算在 DES 的基础上,继续多讲一点,也就是 3 重 DES ...

  10. 5.Java 加解密技术系列之 DES

    Java 加解密技术系列之 DES 序 背景 概念 基本原理 主要流程 分组模式 代码实现 结束语 序 前 几篇文章讲的都是单向加密算法,其中涉及到了 BASE64.MD5.SHA.HMAC 等几个比 ...

随机推荐

  1. 【easy】746. Min Cost Climbing Stairs 动态规划

    On a staircase, the i-th step has some non-negative cost cost[i]assigned (0 indexed). Once you pay t ...

  2. 【easy】257. Binary Tree Paths 二叉树找到所有路径

    http://blog.csdn.net/crazy1235/article/details/51474128 花样做二叉树的题……居然还是不会么…… /** * Definition for a b ...

  3. [其它]iOS 12.2支持电信VoLTE了,中国电信教你如何开通:只要三步

    iOS 12.2支持电信VoLTE了,中国电信教你如何开通:只要三步 link :https://baijiahao.baidu.com/s?id=1629039609897267682&wf ...

  4. 基于tkinter的GUI编程

    tkinter:tkinter是绑定了Python的TKGUI工具集,就是Python包装的Tcl代码,通过内嵌在Python解释器内部的Tcl解释器实现的,它是Python标准库的一部分,所以使用它 ...

  5. Linux-SFTP/SSH免密码,钥匙登录

    1.原理 登录的客户端要有私钥,被登录的服务器要保存客户端生成的公钥. 2.修改服务器/etc/ssh/sshd_config设置,如下: sudo vi /etc/ssh/sshd_config P ...

  6. mycat+mysql集群:实现读写分离,分库分表

    1.mycat文档:https://github.com/MyCATApache/Mycat-doc       官方网站:http://www.mycat.org.cn/ 2.mycat的优点: 配 ...

  7. javaScript -- touch事件详解(touchstart、touchmove和touchend)

    HTML5中新添加了很多事件,但是由于他们的兼容问题不是很理想,应用实战性不是太强,所以在这里基本省略,咱们只分享应用广泛兼容不错的事件,日后随着兼容情况提升以后再陆续添加分享.今天为大家介绍的事件主 ...

  8. ASP.NET Core微服务 on K8S学习笔记(第一章:详解基本对象及服务发现)

    课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务1:课程介绍 任务2:Labels and Selectors 所有资源对 ...

  9. Python OpenCV 图像相识度对比

    强大的openCV能做什么我就不啰嗦,你能想到的一切图像+视频处理. 这里,我们说说openCV的图像相似度对比, 嗯,说好听一点那叫图像识别,但严格讲, 图像识别是在一个图片中进行类聚处理,比如图片 ...

  10. swoole websocket服务推送

    用过workerman, 两个字"好用",对于swoole最近有时间也研究研究 swoole的websocket 很好实现 如官网 https://wiki.swoole.com/ ...