Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的三重DES加密C#-解密_Java_C#_Encryption_Tripledes - Fatal编程技术网

Java中的三重DES加密C#-解密

Java中的三重DES加密C#-解密,java,c#,encryption,tripledes,Java,C#,Encryption,Tripledes,我从客户端服务器得到一个三重DES解密字符串,该字符串已用c#编码(见下文): 示例输出将是输入/输出将是“12345678901344”,然而,我得到的是杂乱无章的返回,例如��0�8.��/0�� 所以c#和java之间有些东西丢失了。。。 这是我上一个问题的后续部分 我非常感谢你在这方面的帮助 代码更改 c#解密代码 使用System.IO; 使用制度; 使用System.Security.Cryptography; 使用系统集合; 使用系统文本; 班级计划 { 静态void Main()

我从客户端服务器得到一个三重DES解密字符串,该字符串已用c#编码(见下文):

示例输出将是输入/输出将是
“12345678901344”
,然而,我得到的是杂乱无章的返回,例如��0�8.��/0�� 所以c#和java之间有些东西丢失了。。。 这是我上一个问题的后续部分

我非常感谢你在这方面的帮助

代码更改

c#解密代码

使用System.IO;
使用制度;
使用System.Security.Cryptography;
使用系统集合;
使用系统文本;
班级计划
{
静态void Main()
{
控制台.WriteLine(“你好,世界!”);
var加密=三重加密(“1D30CC3DE1641D7F5E821D13FC1200C3”、“C9AF269DF8A78A06D1216BFFF8F0536A”);
控制台写入线(加密);
}
公共静态字符串三重加密(字符串加密文本、字符串strKey)
{
字符串errorMessage=“”;
int errorCode=0;
字符串strDecryptedText=“”;
尝试
{
byte[]bytEncryptedChunk=新字节[8];
byte[]bytClearTextChunk=新字节[8];
字节[]_bytespempy=新字节[8];
int字节数=0;
int positionCount=0;
ArrayList输入=新的ArrayList();
ArrayList输出=新的ArrayList();
TripleDESCryptoServiceProvider tdes=(TripleDESCryptoServiceProvider)TripleDESCryptoServiceProvider.Create();
tdes.Key=HexToByteArray(strKey);
tdes.Mode=CipherMode.ECB;
ICryptoTransform tdesDecrypt=tdes.CreateDecryptor();
BytesCount=加密文本长度;
对于(int i=0;i
这将返回输入加密12345678901344的内容。在C代码中,使用ASCII:

bytClearText = ASCIIEncoding.ASCII.GetBytes(strClearText);
在Java中使用UNICODE时:

byte[] encryptKeyBytes = encryptKey.getBytes(UNICODE_FORMAT);
尝试将C#更改为使用UNICODE,或将java代码更改为使用ASCII

此外,由于C#填充了输出:

strEncryptedChar = strEncryptedChar.PadLeft(2, Convert.ToChar("0"));
您可能必须检查以删除加密字符串中的所有“00”,因此1D30CC3DE1641D7F5E821D13FC1200C3将变为1D30CC3DE1641D7F5E821D13FC12C3

(您必须检查它是否在十六进制表达式的边界内:1C01A1可能应该修改,因为它在第二个十六进制1C01 A1:1C1A1

上有一个填充,您可以使用 用unicode代替java代码中的UTF-8

用c#加密:

对于c#中的解码,您可以使用:

现在,对于java加密,您可以使用:

private String\u encrypt2(字符串明文,字符串密钥)
{
尝试
{
/**
*创建md5
*/
MessageDigest md=MessageDigest.getInstance(“md5”);
byte[]digestOfPassword=md.digest(key.getBytes(“UTF-16LE”);
byte[]keyBytes=Arrays.copyOf(digestOfPassword,24);
对于(int j=0,k=16;j<8;)
{
keyBytes[k++]=keyBytes[j++];
}
SecretKey SecretKey=newsecretkeyspec(keyBytes,0,24,“DESede”);
IvParameterSpec iv=新的IvParameterSpec(新字节[8]);
Cipher Cipher=Cipher.getInstance(“DESede/CBC/PKCS5Padding”);
cipher.init(cipher.ENCRYPT_模式,secretKey,iv);
字节[]明文字节=明文.getBytes(“UTF-16LE”);
字节[]密文=cipher.doFinal(明文字节);
字符串输出=Base64.encodeToString(密文,Base64.DEFAULT);
返回输出;
}
捕获(例外情况除外){}
返回“”;
}
对于java中的解密:

private String\u decrypt2(字符串加密文本,字符串密钥)
{
MessageDigest md=null;
字节[]为空;
尝试
{
byte[]message=Base64.decode(encryptext.getBytes(“UTF-16LE”),Base64.DEFAULT);
/**
*制造md5
*/
md=MessageDigest.getInstance(“md5”);
digestOfPassword=md.digest(key.getBytes(“UTF-16LE”);
byte[]keyBytes=Arrays.copyOf(digestOfPassword,24);
对于(int j=
using System.IO;
using System;
using System.Security.Cryptography;
using System.Collections;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");

        var encryption = TripleDESDecrypt("1D30CC3DE1641D7F5E821D13FC1200C3", "C9AF269DF8A78A06D1216BFFF8F0536A");
        Console.WriteLine(encryption);

    }

      public static string TripleDESDecrypt(string strEncryptedText, string strKey)
        {
            string errorMessage = "";
            int errorCode = 0;
            string strDecryptedText = "";

            try
            {
                byte[] bytEncryptedChunk = new byte[8];
                byte[] bytClearTextChunk = new byte[8];
                byte[] _bytesEmpty = new byte[8];
                int BytesCount = 0;
                int positionCount = 0;


                ArrayList Input = new ArrayList();
                ArrayList Output = new ArrayList();

                TripleDESCryptoServiceProvider tdes = (TripleDESCryptoServiceProvider)TripleDESCryptoServiceProvider.Create();

                tdes.Key = HexToByteArray(strKey);
                tdes.Mode = CipherMode.ECB;

                ICryptoTransform tdesDecrypt = tdes.CreateDecryptor();

                BytesCount = strEncryptedText.Length;

                for (int i = 0; i < BytesCount; i += 2)
                {
                    if (positionCount == 8)
                    {
                        positionCount = 0;
                        Input.Add(bytEncryptedChunk);
                        bytEncryptedChunk = new byte[8];
                    }

                    bytEncryptedChunk[positionCount] = byte.Parse(strEncryptedText.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
                    positionCount++;
                }

                if (positionCount != 0)
                {
                    Input.Add(bytEncryptedChunk);
                }

                foreach (byte[] Cbyte in Input)
                {
                    tdesDecrypt.TransformBlock(Cbyte, 0, 8, _bytesEmpty, 0);
                    tdesDecrypt.TransformBlock(Cbyte, 0, 8, bytClearTextChunk, 0);
                    Output.Add(bytClearTextChunk);
                    bytClearTextChunk = null;
                    bytClearTextChunk = new byte[8];
                }

                foreach (byte[] Cbyte in Output)
                {
                    strDecryptedText += ASCIIEncoding.ASCII.GetString(Cbyte);
                }
            }
            catch (Exception ex)
            {
                errorCode = 1;
                errorMessage = ex.Message;


            }
Console.WriteLine(strDecryptedText);
            return strDecryptedText;
        }

        private static byte[] HexToByteArray(string strHex)
        {
            byte[] bytArray = new byte[strHex.Length / 2];
            int positionCount = 0;

            for (int i = 0; i < strHex.Length; i += 2)
            {
                bytArray[positionCount] = byte.Parse(strHex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
                positionCount++;
            }
            return bytArray;
        }
}
bytClearText = ASCIIEncoding.ASCII.GetBytes(strClearText);
byte[] encryptKeyBytes = encryptKey.getBytes(UNICODE_FORMAT);
strEncryptedChar = strEncryptedChar.PadLeft(2, Convert.ToChar("0"));
public static string Encrypt2(string clearText,string key)
{
    try
    {
        string encryptedText = "";
        MD5 md5 = new MD5CryptoServiceProvider();
        TripleDES des = new TripleDESCryptoServiceProvider();
        des.KeySize = 128;
        des.Mode = CipherMode.CBC;
        des.Padding = PaddingMode.PKCS7;

        byte[] md5Bytes = md5.ComputeHash(Encoding.Unicode.GetBytes(key));

        byte[] ivBytes = new byte[8];


        des.Key = md5Bytes;

        des.IV = ivBytes;

        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);

        ICryptoTransform ct = des.CreateEncryptor();
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            encryptedText = Convert.ToBase64String(ms.ToArray());
        }
        return encryptedText;
    }
    catch (Exception exception)
    {
        return "";
    }
}
public static string Decrypt2(string cipher,string key)
{
    try
    {
        byte[] clearBytes = Convert.FromBase64String(cipher);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] md5Bytes = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
        string encryptedText = "";
        TripleDES des = new TripleDESCryptoServiceProvider();
        des.KeySize = 128;
        des.Mode = CipherMode.CBC;
        des.Padding = PaddingMode.PKCS7;
        byte[] ivBytes = new byte[8];
        des.Key = md5Bytes;
        des.IV = ivBytes;
        ICryptoTransform ct = des.CreateDecryptor();
        byte[] resultArray = ct.TransformFinalBlock(clearBytes, 0, clearBytes.Length);
        encryptedText = Encoding.Unicode.GetString(resultArray);
        return encryptedText;
    }
    catch (Exception exception)
    {
        return "";
    }
}
private String _encrypt2(String clearText,String key )
{
    try
    {
        /**
         * create md5
         */
        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8; )
        {
            keyBytes[k++] = keyBytes[j++];
        }


        SecretKey secretKey = new SecretKeySpec(keyBytes, 0, 24, "DESede");
        IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        byte[] plainTextBytes = clearText.getBytes("UTF-16LE");
        byte[] cipherText = cipher.doFinal(plainTextBytes);

        String output = Base64.encodeToString(cipherText,Base64.DEFAULT);
        return output;
    }
    catch (Exception ex) {}
    return "";
}
private String _decrypt2(String encryptText,String key)
{

    MessageDigest md = null;
    byte[] digestOfPassword = null;

    try
    {
        byte[] message = Base64.decode(encryptText.getBytes("UTF-16LE"), Base64.DEFAULT);

        /**
         * make md5
         */
        md = MessageDigest.getInstance("md5");
        digestOfPassword = md.digest(key.getBytes("UTF-16LE"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8; )
        {
            keyBytes[k++] = keyBytes[j++];
        }

        SecretKey secretKey = new SecretKeySpec(keyBytes, 0, 24, "DESede");
        IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] cipherText = cipher.doFinal(message);

        return new String(cipherText, "UTF-16LE");
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch (InvalidKeyException e)
    {
        e.printStackTrace();
    }
    catch (InvalidAlgorithmParameterException e)
    {
        e.printStackTrace();
    }
    catch (NoSuchPaddingException e)
    {
        e.printStackTrace();
    }
    catch (BadPaddingException e)
    {
        e.printStackTrace();
    }
    catch (IllegalBlockSizeException e)
    {
        e.printStackTrace();
    }
    return "";
}
 public static byte[] byteArrayConcat(byte[] array1, byte[] array2) {
        byte[] result = new byte[array1.length + array2.length];
        System.arraycopy(array1, 0, result, 0, array1.length);
        System.arraycopy(array2, 0, result, array1.length, array2.length);
        return result;
    }


 private byte[] fGPKeyTo3DESKey(byte[] GPKey) {

        byte[] _3DESKey = new byte[24];
        byte[] tmp = new byte[8];

        arraycopy(GPKey, 0, tmp, 0, 8);

        _3DESKey = DaPlugUtils.byteArrayConcat(GPKey, tmp);

        return _3DESKey;
    }
 private static byte[] hexStringtoByteArray(String hex) {
        int len = hex.length();

        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
public String desDecryptPin(String pin, String encryptKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {

        int bytesCount = 0;
        int positionCount = 0;


        byte[] bytEncryptedChunk = new byte[8];

        ArrayList<byte[]> Input = new ArrayList();
        bytesCount = pin.length();

        for (int i = 0; i < bytesCount; i += 2) {
            if (positionCount == 8) {
                positionCount = 0;
                Input.add(bytEncryptedChunk);
                bytEncryptedChunk = new byte[8];
            }
            bytEncryptedChunk[positionCount] = (byte) (Integer.parseInt(pin.substring(i, i + 2), 16));
            positionCount++;
        }

        if (positionCount != 0) {
            Input.add(bytEncryptedChunk);
        }


        byte[] _3DESKey = fGPKeyTo3DESKey(hexStringtoByteArray(encryptKey));

        DESedeKeySpec keySpec = new DESedeKeySpec(_3DESKey);
        SecretKey k = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, k);


        String res = "";

        for (byte[] bs : Input) {
            byte[] decryptPin = cipher.doFinal(bs);
            String a = new String(decryptPin, StandardCharsets.US_ASCII);

            res += a;
        }

        return res.trim();
    }