C#和JAVA 3DES的CBC模式加密解密

最近因為需要和外部系統(tǒng)進行通信,數(shù)據(jù)交互基于3DES的CBC模式。因為2種語言對算法的實現(xiàn)有差異性,一開始準(zhǔn)備面向搜索引擎編程的,結(jié)果發(fā)現(xiàn)網(wǎng)上的解決方案都不能使用, 全部報錯!Google也翻了50頁,最終無奈自己實現(xiàn)了。廢話不多說直接上代碼!

C#代碼

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

namespace HM.Framework
{
    /// <summary>
    /// 加密工具類
    /// </summary>
    public static class EncryUtils
    {
        /// <summary>
        /// 3DES加密CBC模式
        /// </summary>
        /// <param name="text">明文(待加密)</param>
        /// <param name="key">加密密鑰</param>
        /// <param name="iv">向量</param>
        /// <returns></returns>
        public static string TripleDesEncryptorCBC(string text, string key, string iv)
        {
            var tripleDESCipher = new TripleDESCryptoServiceProvider();
            tripleDESCipher.Mode = CipherMode.CBC;
            tripleDESCipher.Padding = PaddingMode.PKCS7;
            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[24];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            System.Array.Copy(pwdBytes, keyBytes, len);
            tripleDESCipher.Key = keyBytes;
            tripleDESCipher.IV = Encoding.ASCII.GetBytes(iv);

            ICryptoTransform transform = tripleDESCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(text);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }

        /// <summary>
        /// 3DES解密CBC模式
        /// </summary>
        /// <param name="text"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string TripleDesDecryptorCBC(string text,string key,string iv)
        {
            var tripleDESCipher = new TripleDESCryptoServiceProvider();
            tripleDESCipher.Mode = CipherMode.CBC;
            tripleDESCipher.Padding = PaddingMode.PKCS7;
            
            byte[] encryptedData = Convert.FromBase64String(text);
            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[24];
            byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            System.Array.Copy(pwdBytes, keyBytes, len);
            tripleDESCipher.Key = keyBytes;          
            tripleDESCipher.IV = ivBytes;
            ICryptoTransform transform = tripleDESCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }

        /// <summary>
        /// 類測試
        /// </summary>
        public static void Test()
        {
            var text = "AAABBBCCC啦啦啦啦AABB11";
            var key = "PR3tmPJqcH5RE0iGsW4qiN5VYtjX7sVU";
            var iv = "87654321";


            var encryptData = EncryUtils.TripleDesEncryptorCBC(text, key, iv);
            var decryptorData = EncryUtils.TripleDesDecryptorCBC(encryptData, key, iv);
            Console.WriteLine("原始字符串:{0}", text);
            Console.WriteLine("加密后的值:{0}", encryptData);
            Console.WriteLine("解密后的值:{0}", decryptorData);
        }
    
    }
}

JAVA代碼

package com.songm.pcp.common.util;


import java.security.Key;
import java.security.MessageDigest;
import java.util.Map;

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

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


public class Des {

    // 向量
    private final static String iv = "87654321";
    // 加解密統(tǒng)一使用的編碼方式
    private final static String encoding = "UTF-8";
    /**
     * 3DES加密
     * @param plainText 普通文本
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String encode(String plainText,String secretKey){
        try{
            Key deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            return Base64Utils.encode(encryptData);
            //byte[] bb =  Base64Utils.encode(encryptData);
           
           // return new String(bb,"UTF-8");
        }catch(Exception e){
            e.printStackTrace();
        }
        return plainText;
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText,String secretKey){
        try{
            Key deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

            //byte[] decryptData = cipher.doFinal(Des3Base64.decode(encryptText));
            byte[] decryptData = cipher.doFinal(Base64Utils.decode(encryptText));
            return new String(decryptData, encoding);
        }catch(Exception e){
            e.printStackTrace();
        }
        return encryptText;
    }

    
    public static void main(String[] args) {

        String text = "AAABBBCCC啦啦啦啦AABB11";
        String key = "PR3tmPJqcH5RE0iGsW4qiN5VYtjX7sVU";
        String encryptData = encode(text, key);
        String decryptorData = decode(encryptData, key);
        System.out.println("原始字符串:" + text);
        System.out.println("加密后的值" + encryptData);
        System.out.println("解密后的值" + decryptorData);
    }
        
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容