使用C#加密及解密字符串
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text; namespace Utility
{
/// <summary>
/// http://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string
/// </summary>
public class Encryptor
{
private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5"); // update by yourself public static string Encrypt(string text)
{
var s = DateTime.Now.Year.ToString().Substring(, );
return EncryptStringAES(text, s);
} public static string Decrypt(string text)
{
var s = DateTime.Now.Year.ToString().Substring(, );
return DecryptStringAES(text, s);
} /// <summary>
/// Encrypt the given string using AES. The string can be decrypted using
/// DecryptStringAES(). The sharedSecret parameters must match.
/// </summary>
/// <param name="plainText">The text to encrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for encryption.</param>
public static string EncryptStringAES(string plainText, string sharedSecret)
{
if (string.IsNullOrEmpty(plainText))
throw new ArgumentNullException("plainText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret"); string outStr = null; // Encrypted string to return
RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data. try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / ); // Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), , sizeof(int));
msEncrypt.Write(aesAlg.IV, , aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
} // Return the encrypted bytes from the memory stream.
return outStr;
} /// <summary>
/// Decrypt the given string. Assumes the string was encrypted using
/// EncryptStringAES(), using an identical sharedSecret.
/// </summary>
/// <param name="cipherText">The text to decrypt.</param>
/// <param name="sharedSecret">A password used to generate a key for decryption.</param>
public static string DecryptStringAES(string cipherText, string sharedSecret)
{
if (string.IsNullOrEmpty(cipherText))
throw new ArgumentNullException("cipherText");
if (string.IsNullOrEmpty(sharedSecret))
throw new ArgumentNullException("sharedSecret"); // Declare the RijndaelManaged object
// used to decrypt the data.
RijndaelManaged aesAlg = null; // Declare the string used to hold
// the decrypted text.
string plaintext = null; try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create the streams used for decryption.
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
// Create a RijndaelManaged object
// with the specified key and IV.
aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / );
// Get the initialization vector from the encrypted stream
aesAlg.IV = ReadByteArray(msDecrypt);
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object.
if (aesAlg != null)
aesAlg.Clear();
} return plaintext;
} private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, , rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
} byte[] buffer = new byte[BitConverter.ToInt32(rawLength, )];
if (s.Read(buffer, , buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
} return buffer;
}
}
}
Encryp and decrypt a string via C#
使用C#加密及解密字符串的更多相关文章
- Linux下实现 OpenSSL 简单加密与解密字符串
场景 shell脚本中存在明文密码 客户要求禁止使用明文密码,密码做加密处理. 方案 在网上了解到了Linux OpenSSL加密解密工具 可以指定各种加密算法为字符,文件做加密处理. 加密的案例比较 ...
- 使用Base64进行string的加密和解密 公钥加密—私钥签名
使用Base64进行string的加密和解密 //字符串转bytesvar ebytes = System.Text.Encoding.Default.GetBytes(keyWord);//by ...
- 读取本地json文件,转出为指定格式json 使用Base64进行string的加密和解密
读取本地json文件,转出为指定格式json 引用添加Json.Net 引用命名空间 using Newtonsoft.Json //读取自定目录下的json文件StreamReader sr = ...
- ASP.NET加密和解密数据库连接字符串
大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...
- (译)利用ASP.NET加密和解密Web.config中连接字符串
介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Server, A ...
- 利用ASP.NET加密和解密Web.config中连接字符串
摘自:博客园 介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Se ...
- PHP的加密解密字符串函数
程序中经常使用的PHP加密解密字符串函数 代码如下: /********************************************************************* 函数 ...
- PHP加密解密字符串
项目中有时我们需要使用PHP将特定的信息进行加密,也就是通过加密算法生成一个加密字符串,这个加密后的字符串可以通过解密算法进行解密,便于程序对解密后的信息进行处理. 最常见的应用在用户登录以及一些AP ...
- MVC项目实践,在三层架构下实现SportsStore-10,连接字符串的加密和解密
SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...
随机推荐
- sublime3 快速运行 java
build 系统 Java.sublime-build { "cmd": ["javac $file_name && java $file_base_na ...
- 剑指offer——python【第49题】把字符串转换成整数
题目描述 将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数. 数值为0或者字符串不是一 ...
- Java 读取某文件下的所有文件的大小 并将所有文件的文件名,以及对应大小输出在xls表格里
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.In ...
- HTML、CSS知识点,面试开发都会需要--No.4 内容布局
No.4 内容布局 1.列举场景 同一行布局三个元素.三个元素等比显示,并且其他元素不会围绕这三个元素.如下要让下面的三个column等比显示在一行: 2.通过Float属性实现 (1)float:l ...
- Ubuntu 14.04循环登录问题(密码正确,无法登录)
今天遇到了ubuntu 的循环登录问题,即使输入的密码是正确的,也无法成功登录.查询资料,发现有各种问题引起的循环登录问题,比如安装了jdk,或者安装了驱动. 最后找到了问题的原由:我的电脑是双显卡, ...
- swp文件已存在
vim编辑某个文件时,提示.xxx.sh.swp文件已存在是因为异常退出后,linux会生成一个swp文件,无论选择什么,下次进入还是会提示ll 命令无法看到文件使用 rm -rf .xxx.sh.s ...
- Redis集合 安装 哨兵集群 配置
redis相关 redis基础 redis发布订阅 redis持久化RDB与AOF redis不重启,切换RDB备份到AOF备份 redis安全配置 redis主从同步 redis哨兵集群 redis ...
- [qemu] qemu从源码编译安装
环境:CentOS7-1804 下载最新的源码: ┬─[tong@T7:~/Src/thirdparty/PACKAGES]─[:: AM] ╰─>$ axel https://download ...
- android AsyncTask异步任务(笔记)
AsyncTask是一个专门用来处理后台进程与UI线程的工具.通过AsyncTask,我们可以非常方便的进行后台线程和UI线程之间的交流. 那么AsyncTask是如何工作的哪. AsyncTask拥 ...
- 保存退出vi编辑
保存命令按i进入编辑模式,编辑完成按ESC键 跳到命令模式,然后: :w 保存文件但不退出vi:w file 将修改另外保存到file中,不退出vi:w! 强制保存,不推出vi:wq 保存文件并退出v ...