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