TripleDES对称加密解密 -[C#-JAVA]
C#代码段
先MD5 再TripleDES加密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace WebApplication1
{
public class Class1
{
public static byte[] CRYPTO_KEY = new byte[] { 0x61, 0x75, 0x74, 0x6F, 0x68, 0x6F, 0x6D, 0x65, 0x63, 0x6F, 0x6F, 0x70, 0x65, 0x72, 0x61, 0x74, 0x65, 0x6F, 0x70, 0x65, 0x6E, 0x61, 0x70, 0x69 };
public static byte[] CRYPTO_IV = new byte[] { 0x12, 0x34, 0x56, 0x78, (byte)0x90, (byte)0xAB, (byte)0xCD, (byte)0xEF };
public static String Md5(string str)
{
if (string.IsNullOrWhiteSpace(str)) return str;
StringBuilder sb = new StringBuilder();
MD5 md5 = new MD5CryptoServiceProvider();
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
md5.Clear();
for (int i = 0; i < s.Length; i++)
{
sb.Append(s[i].ToString("x2"));
}
return sb.ToString();
}
//对称加密 并转base64 方法1
public static string TripleDesEncrypt(string str)
{
SymmetricAlgorithm csp = new TripleDESCryptoServiceProvider();
csp.Key = CRYPTO_KEY;
csp.IV = CRYPTO_IV;
csp.Padding = PaddingMode.PKCS7;
ICryptoTransform ct = csp.CreateEncryptor();
byte[] buffer = Encoding.UTF8.GetBytes(str);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
cs.Close();
csp.Clear();
return Convert.ToBase64String(ms.ToArray());
}
//对称加密,并转base64 方法2
public static string encryptToBase64(string plainText)
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
tripleDESCryptoServiceProvider.Key = CRYPTO_KEY;
tripleDESCryptoServiceProvider.IV = CRYPTO_IV;
tripleDESCryptoServiceProvider.Padding = PaddingMode.PKCS7;//补位
//tripleDESCryptoServiceProvider.Mode = CipherMode.ECB;//CipherMode.CBC
CryptoStream cStream = new CryptoStream(mStream,
tripleDESCryptoServiceProvider.CreateEncryptor(),
CryptoStreamMode.Write);
// Convert the passed string to a byte array.
byte[] toEncrypt = Encoding.UTF8.GetBytes(plainText);
// Write the byte array to the crypto stream and flush it.
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return Convert.ToBase64String(ret);
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
}
}
Java 代码片段
- package com.ittx.edi.erp.service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
public class TripleDesEncrypt {
//密钥公共参数
private final byte[] DESkey = {0x61, 0x75, 0x74, 0x6F, 0x68, 0x6F, 0x6D, 0x65, 0x63, 0x6F, 0x6F, 0x70, 0x65, 0x72, 0x61, 0x74, 0x65, 0x6F, 0x70, 0x65, 0x6E, 0x61, 0x70, 0x69};
private final byte[] DESIV = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};// 设置向量,略去
//加密Key/value
private AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现
private SecretKey key = null;
/**
* MD5加密串
*转16进制小写 方法1
* @param s
* @return
*/
public String MD5(String s) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
try {
//StringBuilder sb = new StringBuilder();
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
- /**
* MD5加密转小写16进制 方法2
* @param str
* @param encoding
* @return
*/
static String md5ToHex16(String str,String encoding){
new BigInteger(1, md5Encrypt(str,encoding)).toString(16)
}
static byte[] md5Encrypt(String str,String encoding) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5")
md5.reset()
md5.update(str.getBytes(encoding))
md5.digest()
} catch (Exception ex) {
ex.printStackTrace()
null
}
}
/**
* 获取密钥参数
*
* @throws Exception
*/
public TripleDesEncrypt() throws Exception {
DESedeKeySpec keySpec = new DESedeKeySpec(DESkey);// 设置密钥参数
iv = new IvParameterSpec(DESIV);// 设置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");// 获得密钥工厂
key = keyFactory.generateSecret(keySpec);// 得到密钥对象
}
/**
* 加密方法
*
* @param data
* @return
* @throws Exception
*/
public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(pasByte);
}
/**
* 解密方法
*
* @param data
* @return
* @throws Exception
*/
public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
return new String(pasByte, "UTF-8");
}
// public static void main(String[] args) {
// try {
// String test = "7c9c9ebdc2a0a323cbc0f4d23605fde7";
// TripleDesEncrypt des = new TripleDesEncrypt();//自定义密钥
// String s = des.MD5("[{\"json\":\"123\"}]_20200106_012345678901234567890123");
// String ss = s.toLowerCase();
// System.out.println(ss);
// System.out.println("加密前的字符:"+ss);
// System.out.println("加密后的字符:"+des.encode(ss));
// System.out.println("解密后的字符:"+des.decode(des.encode(ss)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
转载另外一位博友的总结:
https://www.cnblogs.com/jaamy/p/6118622.html
TripleDES对称加密解密 -[C#-JAVA]的更多相关文章
- AES对称加密解密类
import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...
- DESEncrypt对称加密解密
分享一个很好用的DESEncrypt对称加密解密的类 using System; using System.Security.Cryptography; using System.Text; usin ...
- 使用java实现对称加密解密(AES),非对称加密解密(RSA)
对称加密:双方采用同样的秘钥进行加密和解密.特点是速度快,但是安全性没有非对称加密高 非对称加密:接收方生成的公有秘钥公布给发送方,发送方使用该公有秘钥加密之后,发送给接收方,然后接收方使用私有秘钥解 ...
- pyDes 实现 Python 版的 DES 对称加密/解密--转
https://my.oschina.net/leejun2005/blog/586451 手头有个 Java 版的 DES 加密/解密程序,最近想着将其 Python 重构下,方便后续脚本解析,捣鼓 ...
- python AES 双向对称加密解密
高级加密标准(Advanced Encryption Standard,AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用来替代原先的DES,已经被多方分 ...
- AES加密解密算法---java
package com.BFGJ.AES; import java.util.Random; import java.util.StringTokenizer; import javax.crypto ...
- 使用Aes对称加密解密Web.Config数据库连接串
现在很多公司开始为了保证数据库的安全性,通常会对Web.Config的数据库连接字符串进行加密.本文将介绍学习使用Aes加密解密数据库连接字符串.本文采用MySql数据库. AES概念简述 AES 是 ...
- 凯撒加密解密(java字母移位)
1.设计思想:加密就是将字符数据转化为ASC码表中的数字,a—w之间通过加3之后再转化为字符型输出,x—z之间通过转化为ASC码表中的数字后减去23再转化为字符型输出.解密就是将字符数据转化为ASC码 ...
- Des加密解密算法java实现
package tech.fullink.eaglehorn.utils; import javax.crypto.Cipher; import javax.crypto.SecretKey; imp ...
随机推荐
- GYM101810 ACM International Collegiate Programming Contest, Amman Collegiate Programming Contest (2018) M. Greedy Pirate (LCA)
题意:有\(n\)个点,\(n-1\)条边,每条边正向和反向有两个权值,且每条边最多只能走两次,有\(m\)次询问,问你从\(u\)走到\(v\)的最大权值是多少. 题解:可以先在纸上画一画,不难发现 ...
- Python基础--核心数据类型
python的核心数据类型: Number 数字(整数,浮点数,复数,布尔型数) String 字符串 List 列表 Tuple 元组 Dictionary 字典 Set 集合 1. 整数(整型数) ...
- LEETCODE - 160【相交链表】
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode ...
- Hexo-使用阿里iconfont图标
Hexo-使用阿里iconfont图标 因为使用hexo搭建的博客中,大家并不懂都有什么图标,fa fa-xx就懵了,不知道都有什么. 首先,fa fa-xxx中的图标可以在 图标库 中寻找. (上面 ...
- Leetcode(215)-数组中的第K个最大元素
在未排序的数组中找到第 k 个最大的元素.请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素. 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 ...
- Windows 10 & git & bash
Windows 10 & git & bash If you are on Windows, we recommend downloading Git for Windows and ...
- Cocos Creator 游戏开发
Cocos Creator 游戏开发 https://www.cocos.com/products#CocosCreator 一体化编辑器: 包含了一体化.可扩展的编辑器,简化了资源管理.游戏调试和预 ...
- after upgrade macOS Catalina bugs
after upgrade macOS Catalina bugs 升级了macOS catalina后,碰到的 bugs? macOS 10.15.5 https://www.apple.com/m ...
- webpack defineConstants
webpack defineConstants PAGES 全局常量/全局变量 https://webpack.js.org/plugins/define-plugin/ taro https://n ...
- Bootstrap5 多级dropdown
<div class="dropdown"> <a class="btn dropdown-toggle"> Dropdown link ...