在网上搜索到的一个Des加密解密例子代码

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

  • 原文章地址
  • 原文地址:https://www.cnblogs.com/wpwen/p/370167.html