C#DES加密和JAVA互通

编程

之前自己解决过JAVA和C# 对称加密的一个问题,由于C#和JAVA都自己开发,比较方便,通过转成16进制解决问题。所以这次也直接尝试通过转16进制看是否能调接口成功。结果失败了(之前自己问题的链接:DES 加密解密C#和JAVA 互通 )。

 

解决方法

给的JAVA调用示例Demo中使用"DES/ECB/PKCS5Padding"加密,未使用向量iv。

对应C#为  CipherMode.ECB;  PaddingMode.PKCS7;

   public byte[] doECBEncrypt(byte[] plainText, int len) throws Exception {

Cipher cipher = this.getCipher("DES", "DES/ECB/PKCS5Padding", 1, (byte[])null);

byte[] encryptedData = cipher.doFinal(plainText, 0, len);

return encryptedData;

}

protected Cipher getCipher(String factory, String cipherName, int cryptMode, byte[] iv) throws Exception {

SecureRandom sr = new SecureRandom();

byte[] rawKeyData = this.m_desKey;

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(factory);

SecretKey key = new SecretKeySpec(this.m_desKey, factory);

Cipher cipher = Cipher.getInstance(cipherName);

if (iv != null) {

IvParameterSpec ips = new IvParameterSpec(iv);

cipher.init(cryptMode, key, ips, sr);

} else {

cipher.init(cryptMode, key, sr);

}

return cipher;

}

C#对应如下

        /// <summary> /// 加密字符串   

        /// </summary>  

        /// <param name="str">要加密的字符串</param>  

        /// <param name="key">秘钥</param>  

        /// <returns>加密后的字符串</returns>  

        public static string Encrypt_ECB(string str, string myKey)

{

string encryptKeyall = Convert.ToString(myKey);    //定义密钥  

            if (encryptKeyall.Length < 9)

{

for (; ; )

{

if (encryptKeyall.Length < 9)

encryptKeyall += encryptKeyall;

else

break;

}

}

string encryptKey = encryptKeyall.Substring(0, 8);

DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();

byte[] key = Encoding.UTF8.GetBytes(encryptKey); //定义字节数组,用来存储密钥

            byte[] data = Encoding.UTF8.GetBytes(str);//定义字节数组,用来存储要加密的字符串

descsp.Key = key;

descsp.Mode = CipherMode.ECB;

descsp.Padding = PaddingMode.PKCS7;

MemoryStream MStream = new MemoryStream(); //实例化内存流对象    

            //使用内存流实例化加密流对象   

            CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);

CStream.Write(data, 0, data.Length);  //向加密流中写入数据    

            CStream.FlushFinalBlock();              //释放加密流    

            return Convert.ToBase64String(MStream.ToArray());//返回加密后的字符串  

        }

 

以上是 C#DES加密和JAVA互通 的全部内容, 来源链接: utcz.com/z/513458.html

回到顶部