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. 有名的素MM

    from math import sqrt item=[] for yr in [1988,1989]: for mth in range(1,13): if mth in [1,3,5,7,8,10 ...

  2. winform倒计时

    public partial class Form1 : Form { private int Seconds; public Form1() { InitializeComponent(); // ...

  3. source ~/.bash_profile 只生效一次 解决方案

    在~/.zshrc文件最后,增加一行: source ~/.bash_profile

  4. PADS Layout VX.2.3 设置测量精度

    操作系统:Windows 10 x64 工具1:PADS Layout VX.2.3 Pin #7.#8的实际距离是0.65mm,但是测量的结果却是0.7mm.为什么呢?这是由于测量精度的设置不恰当造 ...

  5. Python3学习笔记十五

    ---恢复内容开始--- 1.  jquery的属性操作  $().attr(属性名)    取值 $().attr(属性名,属性值)      赋值 <!DOCTYPE html> &l ...

  6. Canvas中如何画一条清晰的线宽为奇数(如1px逻辑像素)的线?

    我在开发中使用canvas的机会不是很多,但是第一次实际使用中就遇到了问题,"很久很久以前,我自己画了一个雷达图,线宽都是1像素,但是显示效果不如期望,这才发现canvas中的画线还是有坑的 ...

  7. Sentry部署

    前期准备 [root@Aaron ~]# uname -r 3.10.0-327.el7.x86_64 [root@Aaron ~]# uname -a Linux Aaron 3.10.0-327. ...

  8. 当TFS/VSTS遇上Power BI

    引言 众所周知,要对TFS进行深入的图表分析,往往需要依赖于SQL Server Analysis Service和SQL Server Reporting Service.虽然随着TFS对敏捷项目的 ...

  9. 编写一份好的 Vimrc

    编写一份好的 Vimrc 目录 如何 Vimrc 色彩 空白字符与制表符 UI 配置 搜索 折叠 移动 用户自定义的前缀快捷按键 插件CtrlP 启动配置 终端Tmux 自动命令及其分组 备份 自定义 ...

  10. 咸鱼入门到放弃13--监听器(Listener)

    一.监听器介绍 1.1.监听器的概念