des加解密java c#,C#編寫DES加密、解密類

這個C#類封裝的DES加密解密,可以使用默認秘鑰進行加密、解密,也可以自定義秘鑰進行加密、解密,調用簡單方便。

示例一:

using System;

using System.Security.Cryptography;

using System.Text;

namespace DotNet.Utilities

{

///

/// DES加密/解密類。

///

public class DESEncrypt

{

public DESEncrypt()

{

}

#region ========加密========

///

/// 加密

///

///

///

public static string Encrypt(string Text)

{

return Encrypt(Text,"sharejs.com");

}

///

/// 加密數據

///

///

///

///

public static string Encrypt(string Text,string sKey)

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

byte[] inputByteArray;

inputByteArray=Encoding.Default.GetBytes(Text);

des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

System.IO.MemoryStream ms=new System.IO.MemoryStream();

CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,0,inputByteArray.Length);

cs.FlushFinalBlock();

StringBuilder ret=new StringBuilder();

foreach( byte b in ms.ToArray())

{

ret.AppendFormat("{0:X2}",b);

}

return ret.ToString();

}

#endregion

#region ========解密========

///

/// 解密

///

///

///

public static string Decrypt(string Text)

{

return Decrypt(Text,"sharejs.com");

}

///

/// 解密數據

///

///

///

///

public static string Decrypt(string Text,string sKey)

{

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

int len;

len=Text.Length/2;

byte[] inputByteArray = new byte[len];

int x,i;

for(x=0;x

{

i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);

inputByteArray[x]=(byte)i;

}

des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));

System.IO.MemoryStream ms=new System.IO.MemoryStream();

CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);

cs.Write(inputByteArray,0,inputByteArray.Length);

cs.FlushFinalBlock();

return Encoding.Default.GetString(ms.ToArray());

}

#endregion

}

}

示例二:

///

public class Help_Encrypt

{

///

///

///

///

public static string Encode(string str, 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(str);

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"; }

}

///

///

///

///

public static string Decode(string str, 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[] 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();

return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());

}

catch (Exception) { return ""; }

}

}

JAVADES加密解密類

package com.bgxt.messages;

import java.io.UnsupportedEncodingException;

import java.security.*;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

/**

* 字符串工具集合

* @author Liudong

*/

public class StringUtils {

private static final String PASSWORD_CRYPT_KEY = XmlUtil.getConfig().getPasswdKey().substring(0,8);

//private final static String DES = "DES";

//private static final byte[] desKey;

//解密數據

public static String decrypt(String message,String key) throws Exception {

byte[] bytesrc =convertHexString(message);

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);

return new String(retByte);

}

public static byte[] encrypt(String message, String key)

throws Exception {

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"));

}

public static String encrypt(String value){

String result="";

try{

value=java.net.URLEncoder.encode(value, "utf-8");

result=toHexString(encrypt(value, PASSWORD_CRYPT_KEY)).toUpperCase();

}catch(Exception ex){

ex.printStackTrace();

return "";

}

return result;

}

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;

}

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();

}

public static void main(String[] args) throws Exception {

String value="01";

System.out.println("加密數據:"+value);

System.out.println("密碼為:"+XmlUtil.getConfig().getPasswdKey());

String a=encrypt( value);

System.out.println("加密后的數據為:"+a);

}

}

以上所述就是本文的全部內容了,希望大家能夠喜歡。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/536649.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/536649.shtml
英文地址,請注明出處:http://en.pswp.cn/news/536649.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

八年開發程序員淺析SpringBoot 之 Shiro 與 Redis 多級緩存問題

前言 來自不愿意透露姓名的小師弟的投稿。這篇主要講了&#xff0c;項目中配置了多緩存遇到的坑&#xff0c;以及解決辦法。 發現問題 在一次項目實踐中有實現多級緩存其中有已經包括了 Shiro 的 Cache &#xff0c;本以為開啟 redis 的緩存是一件很簡單的事情只需要在啟動類上…

Web端H.265播放器研發解密

音視頻編解碼對于前端工程師是一個比較少涉足的領域&#xff0c;涉及到流媒體技術中的文本、圖形、圖像、音頻和視頻多種理論知識的學習&#xff0c;才能夠應用到具體實踐中&#xff0c;本團隊在多媒體領域深耕兩年多&#xff0c;才算是有一定產出&#xff0c;我們自研web播放器…

拳擊 武術java父類,拳擊是一種很有力量的武術類型

原標題&#xff1a;拳擊是一種很有力量的武術類型拳擊是一種很有力量的武術類型&#xff0c;拳擊比賽策略有很多&#xff0c;圍繩技術是其中之一。那么拳擊比賽策略技巧有哪些呢&#xff1f;下面養生之道網為您解析拳擊比賽策略技巧有哪些&#xff0c;看看吧。1、當拳手靠在圍繩…

捧上天的AI落地困難,“ 不懂變通”的華為云如何應付?

前幾年&#xff0c;AI幾乎被捧上天&#xff0c;各大公司傾巢出動&#xff0c;推出了不少吸眼球的應用和產品。如今&#xff0c;這些AI成果是否真得讓企業從中獲得價值&#xff1f;繞不開的數據、隱私和安全問題作何解&#xff1f;不同領域、不同規模、不同技術能力的企業如何最…

Apache-Flink深度解析-DataStream-Connectors之Kafka

Kafka 簡介Apache Kafka是一個分布式發布-訂閱消息傳遞系統。 它最初由LinkedIn公司開發&#xff0c;LinkedIn于2010年貢獻給了Apache基金會并成為頂級開源項目。Kafka用于構建實時數據管道和流式應用程序。它具有水平擴展性、容錯性、極快的速度&#xff0c;目前也得到了廣泛的…

Java使用繼承的語法是,Java基礎語法八 繼承

1、超類和子類超類和子類父類與子類多態&#xff1a;一個對象變量可以指示多種實際類型的現象稱為多態一個變量可以引用父類對象&#xff0c;也可以引用其子類對象&#xff0c;這就是多態。不能將一個超類的引用賦給子類變量&#xff0c;因為調用子類方法時可能發生運行錯誤子類…

kaka 1.0.0 重磅發布,服務于后端的事件領域模型框架。

百度智能云 云生態狂歡季 熱門云產品1折起>>> kaka 1.0.0正式發布了&#xff0c;從三個月前的kaka-notice-lib 1.0.0的發布&#xff0c;經過多次研磨&#xff0c;終于迎來了本次重大更新。 kaka是一款服務于java后端的事件領域模型框架&#xff0c;主要目的為解耦業…

java配置文件工具類,java項目加載配置文件的工具類

java項目加載配置文件的工具類package com.loadproperties;import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class ConfigUtil {private static InputStream input;private volatile Properties configuration new Properties();/…

如何把WAV格式音頻轉換為MP3格式

WAV為微軟公司&#xff08;Microsoft)開發的一種聲音文件格式&#xff0c;它符合RIFF(Resource Interchange File Format)文件規范&#xff0c;用于保存Windows平臺的音頻信息資源&#xff0c;被Windows平臺及其應用程序所廣泛支持&#xff0c;因此在聲音文件質量和CD相差無幾&…

php 異步處理類,php異步處理類

該類可以請求HTTP和HTTPS協議&#xff0c;還可以處理301、302重定向以及GZIP壓縮等。[PHP]代碼//使用方法require(asynHandle.class.php);$obj new asynHandle();$result $obj->Request(http://baidu.com);$result2 $obj->Get(https://mail.google.com/);echo "{…

惡意軟件盯上了加密貨幣,兩家以色列公司受到攻擊

近日&#xff0c;網絡安全公司Palo Alto Networks威脅研究部門Unit 42發博稱&#xff0c;已確認Cardinal RAT自2017年4月起對兩家從事外匯和加密交易軟件開發的以色列金融科技公司發起過攻擊。 Cardinal RAT是可遠程訪問特洛伊木馬&#xff08;RAT&#xff09;&#xff0c;攻擊…

php 自定義打印模板下載,PHP – 創建自定義模板系統?

我已經在這里搜索過,令人驚訝的是我找不到答案.我發現了一個類似的線程,但沒有真正的解決方案.復雜的部分是循環,如果我不需要循環我可以只是做一個常規替換.所以,我有一個帶有一些標記的.html文件,如下所示&#xff1a;{{startloop}}{{imgname}}{{endLoop}}我想要做的是用其他…

騰訊財報中“最大秘密”:2018云收入91億元,交首份TO B答卷

騰訊財報中“最大秘密”云業務收入又一次被公開了&#xff1a;2018年&#xff0c;騰訊云收入91億元&#xff0c;增長100%。 3月21日&#xff0c;騰訊發布2018年Q4及全年財報&#xff0c;2018全年收入3126.94億元同比增長32%&#xff0c;凈利潤(Non-GAAP)774.69億元。而被列進“…

根據坐標如何在matlab中l連成曲線,matlab中,如何將兩條曲線畫在一個坐標系里,plot(x1,x2,y1,y2)還是怎樣...

matlab中&#xff0c;如何將兩條曲線畫在一個坐標系里&#xff0c;plot(x1,x2,y1,y2)還是怎樣以下文字資料是由(歷史新知網www.lishixinzhi.com)小編為大家搜集整理后發布的內容&#xff0c;讓我們趕快一起來看一下吧&#xff01;matlab中&#xff0c;如何將兩條曲線畫在一個坐…

Android 物聯網 傳感器

前幾天做了一個嵌入式課設。將傳感器收集到的數據傳到手機制作的APP里。 項目中涉及到的主要的java代碼和xml布局文件上傳到了github&#xff0c;https://github.com/123JACK123jack/Android轉載于:https://www.cnblogs.com/libin123/p/10578601.html

java已被弱化簽名,高效Java第四十條建議:謹慎設計方法簽名

作用有助于設計易于學習和使用的API。如何做——謹慎地選擇方法的名稱1.選擇易于理解的&#xff0c;并且與同一個包中的其他名稱風格一致的名稱。2.選擇與大眾認可的名稱相一致的名稱。如何做——不要過于追求提供便利的方法每個方法都應該盡其所能。方法太多會使類難以學習、使…

curl有php內存緩存,PHP CURL內存泄露的解決方法

PHP CURL內存泄露的解決方法curl配置平淡無奇&#xff0c;長時間運行發現一個嚴重問題&#xff0c;內存泄露&#xff01;不論用單線程和多線程都無法避免&#xff01;是curl訪問https站點的時候有bug&#xff01;內存泄露可以通過linux的top命令發現&#xff0c;使用php函數mem…

MySQL學習【第五篇SQL語句上】

一.mysql命令 1.連接服務端命令 1.mysql -uroot -p123 -h127.0.0.1 2.mysql -uroot -p123 -S /tmp/mysql.sock 3.mysql -uroot -p123 -hlocalhost 4.mysql -uroot -p123 2.mysql登陸后的一些命令 1.\h或者help   查看幫助 2.\G       格式化查看數據&#xff08;以k…

phpexcel.php linux,phpexcel在linux系統報錯如何解決

最近有個tp3.2的項目遷移到linux系統上了&#xff0c;突然有天發現原本在win server 2008上運行沒問題的excel導出功能在新的系統上不能使用了。報錯如下&#xff1a;說是1762行有問題&#xff0c;找到這個文件的代碼看看&#xff1a;/*** Get an instance of this class** acc…

優雅的redux異步中間件 redux-effect

不吹不黑&#xff0c;redux蠻好用。只是有時略顯繁瑣&#xff0c;叫我定義每一個action、action type、使用時還要在組件上綁定一遍&#xff0c;臣妾做不到呀&#xff01;下面分享一種個人比較傾向的極簡寫法&#xff0c;仍有待完善&#xff0c;望討論。 github: github.com/li…