C# Java 相互加密解密(DES对称加密方式)

分类:C#     发布:2020-04-24     来源:本站     浏览:168 次
JAVA和.NET的系统类库里都有封装DES对称加密的实现方式,但是对外暴露的接口却各不相同,甚至有时会让自己难以解决其中的问题,比如JAVA加密后的结果在.NET中解密不出来等,由于最近项目有跨JAVA和.NET的加解密,经过我的分析调试,终于让它们可以互相加密解密了。直接上代码

C# 代码
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

/// <summary>
///     DES3加密解密
/// </summary>
public class Des3
{
    public static void Main()
    {

        byte[] key = Convert.FromBase64String("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"); //key为abcdefghijklmnopqrstuvwx的Base64编码
        byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
        var data = Encoding.UTF8.GetBytes("中国ABCabc123:{}");

        Console.WriteLine("ECB模式:");//当模式为ECB时,IV无用
        var encode = Des3EncodeECB(key, iv, data);
        var decode = Des3DecodeECB(key, iv, encode);
        Console.WriteLine("加密:" + Convert.ToBase64String(encode));
        Console.WriteLine("解密:" + Encoding.UTF8.GetString(decode));
        Console.WriteLine();

        Console.WriteLine("CBC模式:");
        encode = Des3EncodeCBC(key, iv, data);
        decode = Des3DecodeCBC(key, iv, encode);
        Console.WriteLine("加密:" + Convert.ToBase64String(encode));
        Console.WriteLine("解密:" + Encoding.UTF8.GetString(decode));
        Console.WriteLine();

        Console.Read();
    }

    #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)
    {
        try
        {
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                var provider = new TripleDESCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                using (var stream = new CryptoStream(memoryStream, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
                {
                    stream.Write(data, 0, data.Length);
                    stream.FlushFinalBlock();
                    bytes = memoryStream.ToArray();
                    stream.Close();
                }
                memoryStream.Close();
            }
            return bytes;
        }
        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
        {
            var memoryStream = new MemoryStream(data);
            var provider = new TripleDESCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            {
                bytes = new byte[data.Length];
                stream.Read(bytes, 0, bytes.Length);
            }
            return bytes;
        }
        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="data">明文的byte数组</param>
    /// <returns>密文的byte数组</returns>
    public static byte[] Des3EncodeECB(byte[] key, byte[] iv, byte[] data)
    {
        try
        { 
            var memoryStream = new MemoryStream();
            var provider = new TripleDESCryptoServiceProvider {Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                stream.Write(data, 0, data.Length);
                stream.FlushFinalBlock(); 
                bytes = memoryStream.ToArray(); 
                stream.Close();
            }
            memoryStream.Close(); 
            return bytes;
        }
        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="data">密文的byte数组</param>
    /// <returns>明文的byte数组</returns>
    public static byte[] Des3DecodeECB(byte[] key, byte[] iv, byte[] data)
    {
        try
        { 
            var memoryStream = new MemoryStream(data);
            var provider = new TripleDESCryptoServiceProvider {Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            {
                bytes = new byte[data.Length]; 
                stream.Read(bytes, 0, bytes.Length);
            }
            return bytes;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }
    #endregion
}
Java 代码
import java.security.Key;
import java.util.Base64;

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 = decryptBASE64("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4");// key为abcdefghijklmnopqrstuvwx的Base64编码
		byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
		byte[] data = "中国ABCabc123:{}".getBytes("UTF-8");

		System.out.println("ECB模式:");// 当模式为ECB时,IV无用
		byte[] encode = des3EncodeECB(key, data);
		byte[] decode = ees3DecodeECB(key, encode);
		System.out.println("加密:" + encryptBASE64(encode));
		System.out.println("解密:" + new String(decode, "UTF-8"));
		System.out.println();

		System.out.println("CBC模式:");
		encode = des3EncodeCBC(key, keyiv, data);
		decode = des3DecodeCBC(key, keyiv, encode);
		System.out.println("加密:" + encryptBASE64(encode));
		System.out.println("解密:" + new String(decode, "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 factory = SecretKeyFactory.getInstance("desede");
		deskey = factory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, deskey);
		byte[] out = cipher.doFinal(data);
		return out;
	}

	/**
	 * 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 factory = SecretKeyFactory.getInstance("desede");
		deskey = factory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, deskey);
		byte[] out = cipher.doFinal(data);
		return out;
	}

	/**
	 * 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 factory = SecretKeyFactory.getInstance("desede");
		deskey = factory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
		byte[] out = cipher.doFinal(data);
		return out;
	}

	/**
	 * 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 factory = SecretKeyFactory.getInstance("desede");
		deskey = factory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
		byte[] out = cipher.doFinal(data);
		return out;
	}

	// Base64解码
	public static String encryptBASE64(byte[] data) {
		Base64.Encoder encoder = Base64.getEncoder();
		String encode = encoder.encodeToString(data);
		return encode;
	}

	// Base64编码
	public static byte[] decryptBASE64(String data) throws Exception {
		Base64.Decoder decoder = Base64.getDecoder();
		byte[] buffer = decoder.decode(data);
		return buffer;
	}
}
运行结果


如果觉得文章对您有帮助,您可以对我进行打赏 ¥1.1 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:基础:nano 终端文本编辑器使用方法

下一篇:没有了