JAVA.C#关于3DES加密的代码转化

现在需要一份Java版的3DES加密。
但是对方给的是一份C#版本的。
求哪个大神帮忙转化一下。
或者告知C#代码的思路。
key是9762D45A7F5F49FDA284FB686A4F99B9
向量是01,02,03,04,05,06,07,08

         public static string EncryptSP(string toEncryptStr, string key, string iv)
        {
            string ErrorDesc = "";

            if (toEncryptStr == "") return "";
            try
            {
                if (key.Length < 24)
                {
                    key = key.PadRight(24, '1');
                }

                byte[] Encrypted, ivArray, keyArray;
                // 获取加密向量和CP密钥
                ivArray = CryptographyUtility.HexStringToByteArray(iv);
                keyArray = Encoding.Default.GetBytes(key);
                if (EncryptSP(keyArray, ivArray, ConvertStringToByteArray(toEncryptStr), out Encrypted))
                {
                    return ByteArrayToHexString(Encrypted);
                }
                else
                    return "";
            }
            catch (Exception e)
            {
                ErrorDesc = e.Message;
                throw new Exception("CommonEncrypt(使用固定Key对字符串进行加密)-》" + ErrorDesc);
            }
            catch
            {
                ErrorDesc = CryptogramErrorDefinition.E_Cryptogram_SYSTEM_ERROR_DESC;
                throw new Exception("CommonEncrypt(使用固定Key对字符串进行加密)-》" + ErrorDesc);
            }
        }

        /// <summary>
        /// 将16进制字符串转换成byte数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static byte[] HexStringToByteArray(string s)
        {
            Byte[] buf = new byte[s.Length / 2];
            for (int i = 0; i < buf.Length; i++)
            {
                buf[i] = (byte)(chr2hex(s.Substring(i * 2, 1)) * 0x10 + chr2hex(s.Substring(i * 2 + 1, 1)));
            }
            return buf;
        }
        /// <summary>
        /// 字符转换成16显示
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static byte chr2hex(string chr)
        {
            switch (chr)
            {
                case "0":
                    return 0x00;
                case "1":
                    return 0x01;
                case "2":
                    return 0x02;
                case "3":
                    return 0x03;
                case "4":
                    return 0x04;
                case "5":
                    return 0x05;
                case "6":
                    return 0x06;
                case "7":
                    return 0x07;
                case "8":
                    return 0x08;
                case "9":
                    return 0x09;
                case "A":
                    return 0x0a;
                case "B":
                    return 0x0b;
                case "C":
                    return 0x0c;
                case "D":
                    return 0x0d;
                case "E":
                    return 0x0e;
                case "F":
                    return 0x0f;
            }
            return 0x00;
        }
        /// <summary>
        /// 加密(3DES)
        /// </summary>
        /// <param name="KEY">加密密钥</param>
        /// <param name="IV">加密向量</param>
        /// <param name="TobeEncrypted">加密字符串</param>
        /// <param name="Encrypted">加密后Byte数组</param>
        /// <returns></returns>
        public static bool EncryptSP(byte[] KEY, byte[] IV, byte[] TobeEncrypted, out  byte[] Encrypted)
        {
            string ErrorDesc = "";
            if (KEY == null || IV == null)
                throw new Exception("Encrypt(加密)-》" + ErrorDesc);
            Encrypted = null;
            try
            {
                byte[] tmpiv = { 0, 1, 2, 3, 4, 5, 6, 7 };
                for (int ii = 0; ii < 8; ii++)
                {
                    tmpiv[ii] = IV[ii];
                }
                byte[] tmpkey = { 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7 };
                for (int ii = 0; ii < 24; ii++)
                {
                    tmpkey[ii] = KEY[ii];
                }
                //tridesencrypt.Dispose();
                des3.Mode = CipherMode.ECB;
                ICryptoTransform tridesencrypt = des3.CreateEncryptor(tmpkey, tmpiv);
                //tridesencrypt = des.CreateEncryptor(KEY,tmpiv);
                Encrypted = tridesencrypt.TransformFinalBlock(TobeEncrypted, 0, TobeEncrypted.Length);
                //tridesencrypt.Dispose();
                des3.Clear();
                return true;
            }
            catch (Exception e)
            {
                ErrorDesc = e.Message;
                throw new Exception("Encrypt(加密)-》" + ErrorDesc);
            }
            catch
            {
                ErrorDesc = CryptogramErrorDefinition.E_Cryptogram_SYSTEM_ERROR_DESC;
                throw new Exception("Encrypt(加密)-》" + ErrorDesc);
            }
        }
        public static byte[] ConvertStringToByteArray(String s)
        {
            return System.Text.Encoding.GetEncoding("utf-8").GetBytes(s);//gb2312
        }
        public static string ByteArrayToHexString(byte[] buf)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < buf.Length; i++)
            {
                sb.Append(buf[i].ToString("X").Length == 2 ? buf[i].ToString("X") : "0" + buf[i].ToString("X"));
            }
            return sb.ToString();
        }

1个回答

public class Des3Util {
public static void main(String[] args) throws Exception {
byte[] key = new BASE64Decoder()
.decodeBuffer("9762D45A7F5F49FDA284FB686A4F99B9");
byte[] keyiv = { 01,02,03,04,05,06,07,08 };
byte[] data = "GD@2016".getBytes("UTF-8");

    System.out.println("ECB加密解密");
    byte[] str3 = des3EncodeECB(key, data);
    byte[] str4 = ees3DecodeECB(key, str3);
    System.out.println(new BASE64Encoder().encode(str3));
    System.out.println(new String(str4, "UTF-8"));
    System.out.println();
    System.out.println("CBC加密解密");
    byte[] str5 = des3EncodeCBC(key, keyiv, data);
    byte[] str6 = des3DecodeCBC(key, keyiv, str5);
    System.out.println(new BASE64Encoder().encode(str5));
    System.out.println(new String(str6, "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 keyfactory = SecretKeyFactory.getInstance("desede");
    deskey = keyfactory.generateSecret(spec);
    Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, deskey);
    byte[] bOut = cipher.doFinal(data);
    return bOut;
}

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

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

/**
 * 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 keyfactory = SecretKeyFactory.getInstance("desede");
    deskey = keyfactory.generateSecret(spec);
    Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
    IvParameterSpec ips = new IvParameterSpec(keyiv);
    cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
    byte[] bOut = cipher.doFinal(data);
    return bOut;
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问