亲宝软件园·资讯

展开

C#中TripleDES对应Java中的DESede即大家说的3DES,附C#及Java加解密结果一致的控制台程序例子

志在必得Shaun 人气:1

直接上代码了。

Java控制台代码:

package Test;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class Test {
    private static final String encoding = "UTF-8";

    public static void main(String[] args) {
        try {
            String text = "20200121";// 明文
            String key = "Tt3rLPrDIVIhXqAz";// 长度控制为16,作为3DES加密用的key
            String encryptStr = EncryptData(text, key);// 3DES加密结果

            System.out.println("明文:" + text);
            System.out.println("密钥:" + key);
            System.out.println("密文:" + encryptStr);
            System.out.println("解密:" + DecryptData(encryptStr, key));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * DESede加密,key长度为16
     * 
     * @param plainText 明文
     * @param key       密钥
     * @return DESede加密结果
     * @throws Exception
     */
    static String EncryptData(String plainText, String key) throws Exception {

        byte[] keyBytes = key.getBytes(encoding);
        if (keyBytes.length == 16) { // short key ? .. extend to 24 byte key
            byte[] tmpKey = new byte[24];
            System.arraycopy(keyBytes, 0, tmpKey, 0, 16);
            System.arraycopy(keyBytes, 0, tmpKey, 16, 8);
            keyBytes = tmpKey;
        }

        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");

        if (keyBytes.length > 8) {
            byte[] tmpKey = new byte[8];
            System.arraycopy(keyBytes, 0, tmpKey, 0, 8);
            keyBytes = tmpKey;
        }

        IvParameterSpec ips = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(plainText.getBytes(encoding));

        return Base64.encodeBase64String(bOut);
    }

    /**
     * DESede解密,key长度为16
     * 
     * @param input DESede加密的结果
     * @param key   密钥
     * @return DESede解密结果
     * @throws Exception
     */
    static String DecryptData(String input, String key) throws Exception {
        byte[] keyBytes = key.getBytes(encoding);
        if (keyBytes.length == 16) { // short key ? .. extend to 24 byte key
            byte[] tmpKey = new byte[24];
            System.arraycopy(keyBytes, 0, tmpKey, 0, 16);
            System.arraycopy(keyBytes, 0, tmpKey, 16, 8);
            keyBytes = tmpKey;
        }

        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");

        if (keyBytes.length > 8) {
            byte[] tmpKey = new byte[8];
            System.arraycopy(keyBytes, 0, tmpKey, 0, 8);
            keyBytes = tmpKey;
        }

        IvParameterSpec ips = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(Base64.decodeBase64(input));

        return new String(bOut, encoding);
    }

}

C#控制台代码:

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                String text = "20200121";// 明文
                String key = "Tt3rLPrDIVIhXqAz";// 长度控制为16,作为3DES加密用的key
                String encryptStr = EncryptData(text, key);// 3DES加密结果

                Console.WriteLine("明文:" + text);
                Console.WriteLine("密钥:" + key);
                Console.WriteLine("密文:" + encryptStr);
                Console.WriteLine("解密:" + DecryptData(encryptStr, key));
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine("运行异常,异常信息:" + ex.Message + ex.StackTrace);
                Console.WriteLine("按任意键退出重试");
                Console.Read();
            }

        }

        /// <summary>
        /// TripleDES加密,key长度为16
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>TripleDES加密结果</returns>
        public static string EncryptData(string plainText, string key)
        {
            TripleDESCryptoServiceProvider Tripledes = new TripleDESCryptoServiceProvider();
            //Tripledes.Mode = CipherMode.ECB;
            //Tripledes.Padding = PaddingMode.PKCS7;
            byte[] b_input = Encoding.UTF8.GetBytes(plainText);
            byte[] b_key = Encoding.UTF8.GetBytes(key);
            MemoryStream tempStream = new MemoryStream();
            //rgbKey即用于对称算法的密钥、rgbIV即用于对称算法的初始化向量,这里均使用b_key
            CryptoStream encStream = new CryptoStream(tempStream, Tripledes.CreateEncryptor(b_key, b_key), CryptoStreamMode.Write);
            encStream.Write(b_input, 0, b_input.Length);
            encStream.Close();
            return Convert.ToBase64String(tempStream.ToArray());
        }

        /// <summary>
        /// TripleDES解密,key长度为16
        /// </summary>
        /// <param name="input">TripleDES加密的结果</param>
        /// <param name="key">密钥</param>
        /// <returns>TripleDES解密结果</returns>
        public static string DecryptData(string input, string key)
        {
            TripleDESCryptoServiceProvider Tripledes = new TripleDESCryptoServiceProvider();
            byte[] b_input = Convert.FromBase64String(input);
            byte[] b_key = Encoding.UTF8.GetBytes(key);
            MemoryStream tempStream = new MemoryStream();
            //rgbKey即用于对称算法的密钥、rgbIV即用于对称算法的初始化向量,这里均使用b_key
            CryptoStream encStream = new CryptoStream(tempStream, Tripledes.CreateDecryptor(b_key, b_key), CryptoStreamMode.Write);
            encStream.Write(b_input, 0, b_input.Length);
            encStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(tempStream.ToArray());
        }

    }
}

Java和C#运行结果一致,如下:

明文:20200121
密钥:Tt3rLPrDIVIhXqAz
密文:jHaDswvQaPn4ZvashXOTNQ==
解密:20200121

本文首发于我的CSDN博客:https://blog.csdn.net/n_ithero/articlehttps://img.qb5200.com/download-x/details/104061959

加载全部内容

相关教程
猜你喜欢
用户评论