Symmetric encryption and decryption TripleDES - [C # -JAVA]

C # code snippet

MD5 encryption first and then 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 snippets

 

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}; // set vector omitted

// encryption Key / value
private AlgorithmParameterSpec iv = null; // interface parameters of the encryption algorithm, IvParameterSpec achieve a its
Private Key a SecretKey = null;

/ **
* the MD5 encryption string
* lowercase hexadecimal rotation method. 1
* @param S
* @return
* /
public String the MD5 (String S) {
char hexdigits [] = { '0', '. 1', '2', '. 3', '. 4', '. 5', '. 6', '. 7', '. 8', '. 9', 'A', 'B', 'C', 'D', 'E', 'F.'};
the try {
// the StringBuilder the StringBuilder new new SB = ();
byte [] btInput = S.getBytes ();
// get MessageDigest object MD5 digest algorithm
MdInst = MessageDigest.getInstance the MessageDigest ( "the MD5");
// Updates the digest using the specified byte
mdInst.update (btInput);
// obtain the ciphertext
byte [] MD = mdInst.digest ();
// convert ciphertext hexadecimal string into
int J = md.length;
char STR [] = new 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 new String (STR) .toLowerCase ();
} the 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
}
}


/ **
* Get the key parameter
*
* @throws Exception
* /
public TripleDesEncrypt () throws Exception {
DESedeKeySpec keySpec = new new DESedeKeySpec (DESKey); // Set the key parameter
iv = new IvParameterSpec (DESIV); // Set the vector
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ( "DESede") ; // get the key plant
key = keyFactory.generateSecret (keySpec); // key object obtained


}

/ **
* encryption method
*
* @param Data
* @return
* @throws Exception
* /
public String encode (String Data) throws Exception {
Cipher Encipher Cipher.getInstance = ( "a DESede / the CBC / PKCS5Padding"); // get encryption target Cipher
enCipher.init (Cipher.ENCRYPT_MODE, key, iv) ; // set the operating mode encryption mode, and key vector given
byte [] = pasByte enCipher.doFinal (data.getBytes ( "UTF-. 8"));
Base64Encoder = new new Base64Encoder Base64Encoder ();
return base64Encoder.encode (pasByte);
}

/ **
* decryption method
*
* @param Data
* @return
* @throws Exception
* /
public String decode (String Data) throws Exception {
the Cipher DECIPHER the Cipher = .getInstance ( "a DESede / the CBC / PKCS5Padding");
deCipher.init (Cipher.DECRYPT_MODE, Key, IV);
Base64Decoder Base64Decoder new new Base64Decoder = ();

byte [] = pasByte deCipher.doFinal (base64Decoder.decodeBuffer (Data));

return new new String (pasByte, "UTF-. 8");
}
// public static void main (String [] args) {
// the try {
// = Test String "7c9c9ebdc2a0a323cbc0f4d23605fde7";
// new new TripleDesEncrypt TripleDesEncrypt des = (); // custom key
// String s = des.MD5 ( "[ {\" json \ ": \" 123 \ "}] _ 20200106_012345678901234567890123" );
// String SS = s.toLowerCase ();
// System.out.println (SS);
// System.out.println ( "character before encryption:" + SS);
// System.out.println ( "encrypted characters:" + des.encode (SS));
// System.out.println ( "decrypted character:"+ Des.decode (des.encode (ss)));
The catch} // (Exception E) {
// e.printStackTrace ();
//}
//}

}

reprinted Another Friends of Bo summary:
https://www.cnblogs.com/jaamy/p/6118622.html

Guess you like

Origin www.cnblogs.com/joker331/p/12165889.html