asp.net和java這間des加密和解密

來源:互聯網
上載者:User

標籤:digest   logs   .net   代碼   test   asc   tostring   get   利用   

最近有個新項目用java做的,老項目是asp.net,介面傳輸需要des加解密,網上查了些資料,大多數不能拿來就用,自己經過調試加工了一下,具體代碼如下:

密鑰一定是8位

        /// <summary>           /// 利用DES密碼編譯演算法加密字串(可解密)           /// </summary>           /// <param name="pToEncrypt">被加密的字串</param>           /// <param name="key">密鑰(只支援8個位元組的密鑰)</param>           /// <returns>加密後的字串</returns>           public static string DESEnCode(string pToEncrypt, string key)        {            try            {                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();                provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));                provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));                byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(pToEncrypt);                MemoryStream stream = new MemoryStream();                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);                stream2.Write(bytes, 0, bytes.Length);                stream2.FlushFinalBlock();                StringBuilder builder = new StringBuilder();                foreach (byte num in stream.ToArray())                {                    builder.AppendFormat("{0:X2}", num);                }                stream.Close();                return builder.ToString();            }            catch (Exception) { return "xxxx"; }        }         /// <summary>           /// 解密          /// </summary>           /// <param name="plaintext">加密後的字串</param>           /// <param name="key">密鑰(只支援8個位元組的密鑰)</param>           /// <returns>解密後的字串</returns>           public static string Decode(string str, string key, string encLangue)        {            try            {                //str=Ruijie.Pcfg.Utils.DESEncrypt.HexTostring(str);                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();                provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));                provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));                byte[] buffer = new byte[str.Length / 2];                for (int i = 0; i < (str.Length / 2); i++)                {                    int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);                    buffer[i] = (byte)num2;                }                                MemoryStream stream = new MemoryStream();                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);                stream2.Write(buffer, 0, buffer.Length);                stream2.FlushFinalBlock();                stream.Close();                if (encLangue == "java")                {                    return Encoding.GetEncoding("utf-8").GetString(stream.ToArray());                }                else                {                    return Encoding.GetEncoding("gb2312").GetString(stream.ToArray());                }                            }            catch (Exception) { return ""; }        }

 對應java的方法如下:

package com.testspring;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DesHelper {

/**
* 加密
*
*
* **/
public String encrypt(String message,String key)
{
return toHexString(encryptByte(message,key)).toUpperCase();
}
/**
* 明文加密後的數組
*
*
* **/
public byte[] encryptByte(String message, String key) {
byte[] s={};
try
{
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(message.getBytes("UTF-8"));
}
catch (Exception ex) {

}
return s;
}
/**
* 數組轉化成16進位
*
*
* **/
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
/**
* 解密
*ciphertext 加密字串,key 密鑰,encLangue 加密語言
*
* **/
public String decrypt(String ciphertext, String key,String encLangue) {
try {
byte[] bytesrc = convertHexString(ciphertext);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
if(encLangue=="java")
{
return new String(retByte,"utf-8");
}
else
{
return new String(retByte);
}
}
catch (Exception ex)
{

}
return "";
}
/**
* 轉化16進位字串為byte數組
*
* **/
public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}

}

asp.net和java這間des加密和解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.