【加解密】关于DES加密算法的JAVA加密代码及C#解密代码

JAVA加密:

package webdomain;

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 Decoder.BASE64Encoder;

public class CrytoTools {
    private static final byte[] DESkey = "此处8位密钥--A".getBytes();  //
    private static final byte[] DESIV = "此处另外8位密钥--B".getBytes(); //

    static AlgorithmParameterSpec iv = null;
    private static Key key = null;

    public CrytoTools() 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");
        enCipher.init(Cipher.ENCRYPT_MODE , key,iv);
        byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(pasByte);
    }
}

 

C#解密

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Text;

using System.Configuration;
using System.Security.Cryptography;
using System.IO;

namespace AppService
{
    public class DES
    {
        // DES復号化
        public static string DESDeCode(string encryptedString, string sKey)
        {
            try
            {
                byte[] btKey = Encoding.Default.GetBytes("此处8位密钥--A");        // キー
                byte[] btIV = Encoding.Default.GetBytes("此处另8位密钥--B");   // キー
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Convert.FromBase64String(encryptedString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);
                            cs.FlushFinalBlock();
                        }
                        return Encoding.UTF8.GetString(ms.ToArray());
                    }
                    catch
                    {
                        return encryptedString;
                    }

                }
            }
            catch {
                return encryptedString;
            }
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。