在C#中直接引用加密类库比在C中要方便和快速
des_demo.cs代码如下:
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
public class EncryptStringDES {
public static void Main(String[] args) {
if (args.Length < 1) {
Console.WriteLine("Usage: des_demo <string-to-encrypt>", args[0]);
return;
}
// 使用UTF8函数加密输入参数
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] inputByteArray = utf8Encoding.GetBytes(args[0].ToCharArray());
// 方式一:调用默认的DES实现方法DES_CSP.
DES des = DES.Create();
// 方式二:直接使用DES_CSP()实现DES的实体
//DES_CSP DES = new DES_CSP();
// 初始化DES加密的密钥和一个随机的、8比特的初始化向量(IV)
Byte[] key = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
Byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef};
des.Key = key;
des.IV = IV;
// 建立加密流
SymmetricStreamEncryptor sse = des.CreateEncryptor();
// 使用CryptoMemoryStream方法获取加密过程的输出
CryptoMemoryStream cms = new CryptoMemoryStream();
// 将SymmetricStreamEncryptor流中的加密数据输出到CryptoMemoryStream中
sse.SetSink(cms);
// 加密完毕,将结果输出到控制台
sse.Write(inputByteArray);
sse.CloseStream();
// 获取加密数据
byte[] encryptedData = cms.Data;
// 输出加密后结果
Console.WriteLine("加密结果:");
for (int i = 0; i < encryptedData.Length; i++) {
Console.Write("{0:X2} ",encryptedData[i]);
}
Console.WriteLine();
//上面演示了如何进行加密,下面演示如何进行解密
SymmetricStreamDecryptor ssd = des.CreateDecryptor();
cms = new CryptoMemoryStream();
ssd.SetSink(cms);
ssd.Write(encryptedData);
ssd.CloseStream();
byte[] decryptedData = cms.Data;
char[] decryptedCharArray = utf8Encoding.GetChars(decryptedData);
Console.WriteLine("解密后数据:");
Console.Write(decryptedCharArray);
Console.WriteLine();
}
}
编译:
D:\csharp>csc des_demo.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.
运行实例:
D:\csharp>des_demo.exe 使用C#编写DES加密程序的framework
加密结果:
3D 22 64 C6 57 D1 C4 C3 CF 77 CE 2F D0 E1 78 2A 4D ED 7A A8 83 F9 0E 14 E1 BA 38
7B 06 41 8D B5 E9 3F 00 0D C3 28 D1 F9 6D 17 4B 6E A7 41 68 40