C#里的一些加密解密标准函数示例——DES,SHA1,RSA
private byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public string EncryptDES(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
SHA1有如下特性:不可以从消息摘要中复原信息;两个不同的消息不会产生同样的消息摘要。
代码如下:
/// use sha1 to encrypt string
/// </summary>
public string SHA1_Encrypt(string Source_String)
{
byte[] StrRes = Encoding.Default.GetBytes(Source_String);
HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
StrRes = iSHA.ComputeHash(StrRes);
StringBuilder EnText = new StringBuilder();
foreach (byte iByte in StrRes)
{
EnText.AppendFormat("{0:x2}", iByte);
}
return EnText.ToString();
}
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Microsoft.Samples.Security.PublicKey
{
class App
{
// Main entry point
static void Main(string[] args)
{
// Instantiate 3 People for example. See the Person class below
Person alice = new Person("Alice");
Person bob = new Person("Bob");
Person steve = new Person("Steve");
// Messages that will exchanged. See CipherMessage class below
CipherMessage aliceMessage;
CipherMessage bobMessage;
CipherMessage steveMessage;
// Example of encrypting/decrypting your own message
Console.WriteLine("Encrypting/Decrypting Your Own Message");
Console.WriteLine("-----------------------------------------");
// Alice encrypts a message using her own public key
aliceMessage = alice.EncryptMessage("Alice wrote this message");
// then using her private key can decrypt the message
alice.DecryptMessage(aliceMessage);
// Example of Exchanging Keys and Messages
Console.WriteLine();
Console.WriteLine("Exchanging Keys and Messages");
Console.WriteLine("-----------------------------------------");
// Alice Sends a copy of her public key to Bob and Steve
bob.GetPublicKey(alice);
steve.GetPublicKey(alice);
// Bob and Steve both encrypt messages to send to Alice
bobMessage = bob.EncryptMessage("Hi Alice! - Bob.");
steveMessage = steve.EncryptMessage("How are you? - Steve");
// Alice can decrypt and read both messages
alice.DecryptMessage(bobMessage);
alice.DecryptMessage(steveMessage);
Console.WriteLine();
Console.WriteLine("Private Key required to read the messages");
Console.WriteLine("-----------------------------------------");
// Steve cannot read the message that Bob encrypted
steve.DecryptMessage(bobMessage);
// Not even Bob can use the Message he encrypted for Alice.
// The RSA private key is required to decrypt the RS2 key used
// in the decryption.
bob.DecryptMessage(bobMessage);
} // method Main
} // class App
class CipherMessage
{
public byte[] cipherBytes; // RC2 encrypted message text
public byte[] rc2Key; // RSA encrypted rc2 key
public byte[] rc2IV; // RC2 initialization vector
}
class Person
{
private RSACryptoServiceProvider rsa;
private RC2CryptoServiceProvider rc2;
private string name;
// Maximum key size for the RC2 algorithm
const int keySize = 128;
// Person constructor
public Person(string p_Name)
{
rsa = new RSACryptoServiceProvider();
rc2 = new RC2CryptoServiceProvider();
rc2.KeySize = keySize;
name = p_Name;
}
// Used to send the rsa public key parameters
public RSAParameters SendPublicKey()
{
RSAParameters result = new RSAParameters();
try
{
result = rsa.ExportParameters(false);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return result;
}
// Used to import the rsa public key parameters
public void GetPublicKey(Person receiver)
{
try
{
rsa.ImportParameters(receiver.SendPublicKey());
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
public CipherMessage EncryptMessage(string text)
{
// Convert string to a byte array
CipherMessage message = new CipherMessage();
byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());
// A new key and iv are generated for every message
rc2.GenerateKey();
rc2.GenerateIV();
// The rc2 initialization doesnt need to be encrypted, but will
// be used in conjunction with the key to decrypt the message.
message.rc2IV = rc2.IV;
try
{
// Encrypt the RC2 key using RSA encryption
message.rc2Key = rsa.Encrypt(rc2.Key, false);
}
catch (CryptographicException e)
{
// The High Encryption Pack is required to run this sample
// because we are using a 128-bit key. See the readme for
// additional information.
Console.WriteLine("Encryption Failed. Ensure that the" +
" High Encryption Pack is installed.");
Console.WriteLine("Error Message: " + e.Message);
Environment.Exit(0);
}
// Encrypt the Text Message using RC2 (Symmetric algorithm)
ICryptoTransform sse = rc2.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
try
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
message.cipherBytes = ms.ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
return message;
} // method EncryptMessage
public void DecryptMessage(CipherMessage message)
{
// Get the RC2 Key and Initialization Vector
rc2.IV = message.rc2IV;
try
{
// Try decrypting the rc2 key
rc2.Key = rsa.Decrypt(message.rc2Key, false);
}
catch (CryptographicException e)
{
Console.WriteLine("Decryption Failed: " + e.Message);
return;
}
ICryptoTransform ssd = rc2.CreateDecryptor();
// Put the encrypted message in a memorystream
MemoryStream ms = new MemoryStream(message.cipherBytes);
// the CryptoStream will read cipher text from the MemoryStream
CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read);
byte[] initialText = new Byte[message.cipherBytes.Length];
try
{
// Decrypt the message and store in byte array
cs.Read(initialText, 0, initialText.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
// Display the message received
Console.WriteLine(name + " received the following message:");
Console.WriteLine(" " + Encoding.Unicode.GetString(initialText));
} // method DecryptMessage
} // class Person
} // namespace PublicKey
转载于:https://www.cnblogs.com/seoxs/archive/2011/04/21/2023149.html
C#里的一些加密解密标准函数示例——DES,SHA1,RSA相关推荐
- java 文件 加解密_Java实现文件的加密解密功能示例
Java实现文件的加密解密功能示例 发布时间:2020-10-05 22:05:15 来源:脚本之家 阅读:86 作者:FC WORLD!!! 本文实例讲述了Java实现文件的加密解密功能分享给大家供 ...
- python实现加密字符串_Python实现对字符串的加密解密方法示例
本文实例讲述了Python实现对字符串的加密解密方法.分享给大家供大家参考,具体如下: 需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢复中出错. 安 ...
- python如何加密字符串_Python实现对字符串的加密解密方法示例
本文实例讲述了Python实现对字符串的加密解密方法.分享给大家供大家参考,具体如下: 需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢复中出错. 安 ...
- oracle中md5加密解密_Oracle定义DES加密解密及MD5加密函数示例
(1)DES加密函数 create or replace function encrypt_des(p_text varchar2, p_key varchar2) return varchar2 i ...
- python 字符串加密解密_Python实现对字符串的加密解密方法示例
本文实例讲述了Python实现对字符串的加密解密方法.,具体如下: 需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢复中出错. 安装PyCrypto, ...
- php xxtea加密,PHP实现的XXTEA加密解密算法示例
本文实例讲述了PHP实现的XXTEA加密解密算法.分享给大家供大家参考,具体如下: /** * Xxtea 加密实现类 */ class xxtea { private function long2s ...
- java实现文件加密与解密_Java实现文件的加密解密功能示例
本文实例讲述了Java实现文件的加密解密功能分享给大家供大家参考,具体如下: package com.copy.encrypt; import java.io.File; import java.io ...
- java 采用MD5加密解密代码示例(不玩套路, 非标题党, 附带解密代码)
package cn.demo; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; im ...
- python加密解密 sha256_Python下实现的RSA加密/解密及签名/验证功能示例
本文实例讲述了Python下实现的RSA加密/解密及签名/验证功能.分享给大家供大家参考,具体如下: 原文是py2环境,而我的环境是py3,所以对原代码做了修改:decode(), encode() ...
最新文章
- OpenGL开发学习指南二(glfw+glad)
- python进程和线程中的两个锁
- Web前端开发学习误区,你掉进去了没?
- Java 反射取类中类_Java反射机制(二):通过反射取得类的结构
- Bugfree安装与使用
- 装系统缺少硬盘驱动_缺少操作系统-向我学习,请在今年备份您的硬盘!
- 车牌识别算法实践(一):先验知识
- 拉格朗日/柯西中值定理与高考数学计算
- MySQl学习(从入门到精通 1.1)
- 随着员工转为远程办公,Diligent在所有董事会管理平台中提供无缝视频会议接入,确保安全的虚拟董事会议
- Bootstrap系列之模态框(Modal)
- 阿里最全面试116题整理
- nohup ——Linux后台运行命令
- 2.H.265/HEVC —— 帧内预测
- 【JY】YJK前处理参数详解及常见问题分析(一)
- DVWA-Reflected Cross Site Scripting (XSS)
- LeetCode(172) Factorial Trailing Zeroes
- 【数学建模】常用微分方程模型 + 详细手写公式推导 + Matlab代码实现
- 更快学习编程的7个重要技巧
- 数学奥赛狂砍10题!Meta发布全新定理证明器:AI即将接管数学?
热门文章
- 2017届-应届毕业生-兆芯 GPU architecture design校招在线笔试题
- flink編譯hadoop3.1.2(失败,这个问题没有意义,关闭)
- 为什么是hbase而不是mongodb
- Theory Defect in selecting best pruned tree from CCP with Cross-validation
- some understanding of《Inferring Decision Trees Using the Minimum Description Length Principle*》
- 机器学习性能度量(2):错误接受率 (FAR), 错误拒绝率(FRR),EER计算方法,python实现
- windows下 wgl 创建渲染上下文步骤
- php fastcgi,配置apache以fastcgi运行php
- 微服务接入oauth2_微服务权限终极解决方案,Spring Cloud Gateway+Oauth2实现统一认证和鉴权!...
- java定时任务的两种实现方式