C# 加密(Encrypt) 解密(Decrypt) 操作类 java与 C# 可以相互加密解密
public sealed class EncryptUtils
{
#region Base64加密解密
/// <summary>
/// Base64加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <returns></returns>
public static string Base64Encrypt(string input)
{
return Base64Encrypt(input, new UTF8Encoding());
} /// <summary>
/// Base64加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <param name="encode">字符编码</param>
/// <returns></returns>
public static string Base64Encrypt(string input, Encoding encode)
{
return Convert.ToBase64String(encode.GetBytes(input));
} /// <summary>
/// Base64解密
/// </summary>
/// <param name="input">需要解密的字符串</param>
/// <returns></returns>
public static string Base64Decrypt(string input)
{
return Base64Decrypt(input, new UTF8Encoding());
} /// <summary>
/// Base64解密
/// </summary>
/// <param name="input">需要解密的字符串</param>
/// <param name="encode">字符的编码</param>
/// <returns></returns>
public static string Base64Decrypt(string input, Encoding encode)
{
return encode.GetString(Convert.FromBase64String(input));
}
#endregion #region DES加密解密
/// <summary>
/// DES加密
/// </summary>
/// <param name="data">加密数据</param>
/// <param name="key">8位字符的密钥字符串</param>
/// <param name="iv">8位字符的初始化向量字符串</param>
/// <returns></returns>
public static string DESEncrypt(string data, string key, string iv)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), , (int)ms.Length);
} /// <summary>
/// DES解密
/// </summary>
/// <param name="data">解密数据</param>
/// <param name="key">8位字符的密钥字符串(需要和加密时相同)</param>
/// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
/// <returns></returns>
public static string DESDecrypt(string data, string key, string iv)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv); byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
} DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
#endregion #region MD5加密
/// <summary>
/// MD5加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <returns></returns>
public static string MD5Encrypt(string input)
{
return MD5Encrypt(input, new UTF8Encoding());
} /// <summary>
/// MD5加密
/// </summary>
/// <param name="input">需要加密的字符串</param>
/// <param name="encode">字符的编码</param>
/// <returns></returns>
public static string MD5Encrypt(string input, Encoding encode)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(encode.GetBytes(input));
StringBuilder sb = new StringBuilder();
for (int i = ; i < t.Length; i++)
sb.Append(t[i].ToString("x").PadLeft(, ''));
return sb.ToString();
} /// <summary>
/// MD5对文件流加密
/// </summary>
/// <param name="sr"></param>
/// <returns></returns>
public static string MD5Encrypt(Stream stream)
{
MD5 md5serv = MD5CryptoServiceProvider.Create();
byte[] buffer = md5serv.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
foreach (byte var in buffer)
sb.Append(var.ToString("x2"));
return sb.ToString();
} /// <summary>
/// MD5加密(返回16位加密串)
/// </summary>
/// <param name="input"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string MD5Encrypt16(string input, Encoding encode)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string result = BitConverter.ToString(md5.ComputeHash(encode.GetBytes(input)), , );
result = result.Replace("-", "");
return result;
}
#endregion #region 3DES 加密解密 public static string DES3Encrypt(string data, string key)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.Mode = CipherMode.CBC;
DES.Padding = PaddingMode.PKCS7; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(data);
return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, , Buffer.Length));
} public static string DES3Decrypt(string data, string key)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.Mode = CipherMode.CBC;
DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); string result = "";
try
{
byte[] Buffer = Convert.FromBase64String(data);
result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, , Buffer.Length));
}
catch (Exception e)
{ }
return result;
} #endregion #region DESEnCode DES加密-解密
#region DESEnCode DES加密
public static string DESEnCode(string pToEncrypt, string sKey)
{
// string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
#endregion #region DESDeCode DES解密
public static string DESDeCode(string pToDecrypt, string sKey)
{
// HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey);
// HttpContext.Current.Response.End();
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / ];
for (int x = ; x < pToDecrypt.Length / ; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * , ), ));
inputByteArray[x] = (byte)i;
} des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); // return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
#endregion
#endregion
}
EncryptUtils
DES加密 java与 C# 可以相互加密解密两种方法
通过这个方法可以实现java和C#相互加密与解密 并能保持解密出来一致
方法一:通过.NET的key和VI来生成对应于java的key
java:
<span style="color: #888888;">import java.security.Key;
import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class CryptoTools { private static final byte[] DESkey = { (byte) 0x15, (byte) 0xE7,
(byte) 0xA1, (byte) 0x22, (byte) 0x96, (byte) 0x8B, (byte) 0x24,
(byte) 0xFA };// 设置密钥,略去 private static final byte[] DESIV = { (byte) 0xCE, (byte) 0x35, (byte) 0x5,
(byte) 0xD, (byte) 0x98, (byte) 0x91, (byte) 0x8, (byte) 0xA };// 设置向量,略去 static AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现
private static Key key = null; public CryptoTools() throws Exception {
DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
iv = new IvParameterSpec(DESIV);// 设置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
key = keyFactory.generateSecret(keySpec);// 得到密钥对象 } public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DES/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);
} public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DES/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) throws Exception { CryptoTools tools = new CryptoTools();
System.out.println("加密:" + tools.encode("天下"));
System.out.println("解密:" + tools.decode(tools.encode("天下")));
} }</span>
Java代码
方法二:通过java的key来生成对应于.NET的key和VI
C#:
<span style="color: #888888;">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms; using System.Configuration;
using System.Web;
using System.Security.Cryptography;
using System.IO; namespace DES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string jiami = textBox1.Text;
textBox2.Text= DESEnCode(jiami, "");
} public static string DES_Key = ""; #region DESEnCode DES加密
public static string DESEnCode(string pToEncrypt, string sKey)
{
// string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
#endregion #region DESDeCode DES解密
public static string DESDeCode(string pToDecrypt, string sKey)
{
// HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey);
// HttpContext.Current.Response.End();
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / ];
for (int x = ; x < pToDecrypt.Length / ; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * , ), ));
inputByteArray[x] = (byte)i;
} des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); // return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
#endregion private void button2_Click(object sender, EventArgs e)
{
string jiemi = textBox2.Text;
textBox3.Text = DESDeCode(jiemi,"");
} }
}
</span>
C#代码
java:
<span style="color: #888888;">import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; public class Des {
private byte[] desKey; //解密数据
public static String decrypt(String message,String key) throws Exception { byte[] bytesrc =convertHexString(message);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8")); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
} public static byte[] encrypt(String message, String key)
throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); return cipher.doFinal(message.getBytes("UTF-8"));
} public static byte[] convertHexString(String ss)
{
byte digest[] = new byte[ss.length() / 2];
for(int i = 0; i < digest.length; i++)
{
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte)byteValue;
} return digest;
} public static void main(String[] args) throws Exception {
String key = "11111111";
String value="aa";
String jiami=java.net.URLEncoder.encode(value, "utf-8").toLowerCase(); System.out.println("加密数据:"+jiami);
String a=toHexString(encrypt(jiami, key)).toUpperCase(); System.out.println("加密后的数据为:"+a);
String b=java.net.URLDecoder.decode(decrypt(a,key), "utf-8") ;
System.out.println("解密后的数据:"+b); } public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
} return hexString.toString();
} }
</span>
Java代码
3DES加密 java与 C# 可以相互加密解密
这里的KEY采用Base64编码,便用分发,因为Java的Byte范围为-128至127,c#的Byte范围是0-255
核心是确定Mode和Padding,关于这两个的意思可以搜索3DES算法相关文章
一个是C#采用CBC Mode,PKCS7 Padding,Java采用CBC Mode,PKCS5Padding Padding,
另一个是C#采用ECB Mode,PKCS7 Padding,Java采用ECB Mode,PKCS5Padding Padding,
Java的ECB模式不需要IV
对字符加密时,双方采用的都是UTF-8编码
C#代码
/// <summary>
/// DES3加密解密
/// </summary>
public class Des3
{
#region CBC模式**
/// <summary>
/// DES3 CBC模式加密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">IV</param>
/// <param name="data">明文的byte数组</param>
/// <returns>密文的byte数组</returns>
public static byte[] Des3EncodeCBC( byte[] key, byte[] iv, byte[] data )
{
//复制于MSDN
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.CBC; //默认值
tdsp.Padding = PaddingMode.PKCS7; //默认值
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, , data.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 ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 CBC模式解密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">IV</param>
/// <param name="data">密文的byte数组</param>
/// <returns>明文的byte数组</returns>
public static byte[] Des3DecodeCBC( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.CBC;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, , fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
#region ECB模式
/// <summary>
/// DES3 ECB模式加密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">IV(当模式为ECB时,IV无用)</param>
/// <param name="str">明文的byte数组</param>
/// <returns>密文的byte数组</returns>
public static byte[] Des3EncodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream( mStream,
tdsp.CreateEncryptor( key, iv ),
CryptoStreamMode.Write );
// Write the byte array to the crypto stream and flush it.
cStream.Write( data, , data.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 ret;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
/// <summary>
/// DES3 ECB模式解密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="iv">IV(当模式为ECB时,IV无用)</param>
/// <param name="str">密文的byte数组</param>
/// <returns>明文的byte数组</returns>
public static byte[] Des3DecodeECB( byte[] key, byte[] iv, byte[] data )
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream( data );
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream( msDecrypt,
tdsp.CreateDecryptor( key, iv ),
CryptoStreamMode.Read );
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read( fromEncrypt, , fromEncrypt.Length );
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch ( CryptographicException e )
{
Console.WriteLine( "A Cryptographic error occurred: {0}", e.Message );
return null;
}
}
#endregion
/// <summary>
/// 类测试
/// </summary>
public static void Test()
{
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
//key为abcdefghijklmnopqrstuvwx的Base64编码
byte[] key = Convert.FromBase64String( "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4" );
byte[] iv = new byte[] { , , , , , , , }; //当模式为ECB时,IV无用
byte[] data = utf8.GetBytes( "中国ABCabc123" );
System.Console.WriteLine( "ECB模式:" );
byte[] str1 = Des3.Des3EncodeECB( key, iv, data );
byte[] str2 = Des3.Des3DecodeECB( key, iv, str1 );
System.Console.WriteLine( Convert.ToBase64String( str1 ) );
System.Console.WriteLine( System.Text.Encoding.UTF8.GetString( str2 ) );
System.Console.WriteLine();
System.Console.WriteLine( "CBC模式:" );
byte[] str3 = Des3.Des3EncodeCBC( key, iv, data );
byte[] str4 = Des3.Des3DecodeCBC( key, iv, str3 );
System.Console.WriteLine( Convert.ToBase64String( str3 ) );
System.Console.WriteLine( utf8.GetString( str4 ) );
System.Console.WriteLine();
}
}
Java代码
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Des3 {
public static void main(String[] args) throws Exception {
byte[] key=new BASE64Decoder().decodeBuffer("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4");
byte[] keyiv = { , , , , , , , };
byte[] data="中国ABCabc123".getBytes("UTF-8"); System.out.println("ECB加密解密");
byte[] str3 = des3EncodeECB(key,data );
byte[] str4 = ees3DecodeECB(key, str3);
System.out.println(new BASE64Encoder().encode(str3));
System.out.println(new String(str4, "UTF-8"));
System.out.println();
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new BASE64Encoder().encode(str5));
System.out.println(new String(str6, "UTF-8"));
}
/**
* ECB加密,不要IV
* @param key 密钥
* @param data 明文
* @return Base64编码的密文
* @throws Exception
*/
public static byte[] des3EncodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* ECB解密,不要IV
* @param key 密钥
* @param data Base64编码的密文
* @return 明文
* @throws Exception
*/
public static byte[] ees3DecodeECB(byte[] key, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, deskey);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC加密
* @param key 密钥
* @param keyiv IV
* @param data 明文
* @return Base64编码的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
/**
* CBC解密
* @param key 密钥
* @param keyiv IV
* @param data Base64编码的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
throws Exception {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
}
C# 加密(Encrypt) 解密(Decrypt) 操作类 java与 C# 可以相互加密解密的更多相关文章
- DES加密 java与.net可以相互加密解密两种方法
DES加密 java与.net可以相互加密解密两种方法 https://www.cnblogs.com/DrWang/archive/2011/03/30/2000124.html sun.misc. ...
- DES加密 java与.net可以相互加密解密的方法
我.net程序员.今天和java的童鞋交互,单点登录的操作.采用了如下的加密和解密的方式.经过验证,完美结合.通过这个方法可以实现java和C#相互加密与解密 并能保持解密出来一致. 废话少说,上代码 ...
- JAVA中的集合容器操作类
目录 JAVA中的集合容器操作类 List集合 ArrayList的操作方法说明 LinkedList Stack Set Map Queue 总结 JAVA中的集合容器操作类 Java容器类库总共分 ...
- Java 数学操作类
数学操作类 Math类 数学计算操作类 类属性值 Math.E ^ Math.PI 圆周率 类方法 Math类中,一切方法都是 static 型,因为Math类中没有普通属性. round() 方法 ...
- java DES转C#DES加密解密
一个程序用到java的cn.core.jar加密的,需要在.NET 中解密,发现JAVA的des算法与C#的有点区别. 自己不太懂加密解密算法,所以找了个省事的方法,用IKVM.NET,用这个将cn. ...
- 全面解决.Net与Java互通时的RSA加解密问题,使用PEM格式的密钥文件
作者: zyl910 一.缘由 RSA是一种常用的非对称加密算法.所以有时需要在不用编程语言中分别使用RSA的加密.解密.例如用Java做后台服务端,用C#开发桌面的客户端软件时. 由于 .Net.J ...
- oracle加密encrypt,解密decrypt
目录 oracle加密encrypt,解密decrypt 加密 解密 oracle加密encrypt,解密decrypt 有的oracle版本没有加解密函数,以下操作可以手动添加 oracle数据使用 ...
- 加密解密工具类(Java,DES)
一个Java版的DES加密工具类,能够用来进行网络传输数据加密,保存password的时候进行加密. import java.security.Key; import java.security.sp ...
- js读取cookie,并利用encrypt和decrypt加密和解密方法
以下为支持encrypt和decrypt加密和解密方法 eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a ...
随机推荐
- java类继承总结一 父类类型与子类类型之间的转化问题(转)
java类继承总结一 父类类型与子类类型之间的转化问题 本文将通过一个实例描述父类类型与子类类型之间的转化问题,这个很特殊的问题常常会导致一些潜在的危险,让你整整一个晚上都在调试程序以解决一个让人抓狂 ...
- PolyBase 指南
PolyBase 是一种可通过 t-sql 语言访问数据库外部数据的技术.PolyBase is a technology that accesses data outside of the data ...
- 使用Spring MVC创建 REST API
1.REST的基础知识 当谈论REST时,有一种常见的错误就是将其视为“基于URL的Web服务”——将REST作为另一种类型的远程过程调用(remote procedurecall,RPC)机制,就像 ...
- MySQL两个日期字段相减得到秒的方法
一.MySQL中两个DateTime字段相减 假定表名为tblName,两个DateTime字段名分别为beginDateTime,endDateTime,以下是相关两个mysql日期字段相减的SQL ...
- XNA数学库
XNA Math Vectors 在direct3D 9 和10中,包含3D数学库的D3DX库支持向量和其他核心类型的计算.在direct11中,D3DX库不在包含3D数学库,取而代之的是XNA数学库 ...
- UGUI BUG
UNITY UGUI问题:父类使用 GroupLayout,子类使用contentsize filter时,会出现运行时布局重叠,但隐藏后再显示就会好了.
- 学习ios一段过程后的思考
现在回想起来,学习ios也有一段时间了,大概三个月不到吧,本来是搞linux驱动,刚开始来公司就我一个人负责驱动的东西,主要就是一些bug的解决,后来系统基本上稳定了,我就闲下来了,公司又有些移动医疗 ...
- cdoj1088-王之迷宫 (三维迷宫最短路径)【BFS】
http://acm.uestc.edu.cn/#/problem/show/1088 王之迷宫 Time Limit: 3000/1000MS (Java/Others) Memory Li ...
- 【CodeForces - 235C】Cyclical Quest 【后缀自动机】
题意 给出一个字符串s1和q个询问,每个询问给出一个字符串s2,问这个询问的字符串的所有不同的周期串在s1中出现的次数的和. 分析 对于s1建后缀自动机.对于询问的每个字符串s2,我们按照处理循环串的 ...
- 785. Is Graph Bipartite?从两个集合中取点构图
[抄题]: Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is ...