求一个C# 现成能用的字符串加密、解密函数。好的马上给分结贴!!!!

zjgenius 2004-10-13 07:49:15
要求:
1、C#程序格式 public string encode(string ss) 、public string decode(string ss)

2、要求,任意输入的一个字符串,都能转换成固定长度的加密后的密文。不是字符串短密文就短,字符串长密文就长。

3、最好用DES加密方式。那种 加减乘除的加密就算了。

4、需要引用的动态库请注明。
...全文
720 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
jenet 2005-02-23
  • 打赏
  • 举报
回复
shoucang
MyXQ 2005-02-04
  • 打赏
  • 举报
回复
mark
aresteed 2004-10-18
  • 打赏
  • 举报
回复
不错,收藏,谢谢!
lifeixie 2004-10-18
  • 打赏
  • 举报
回复
楼住需要的是移位加密法,比如把8位一个字节压缩成6位一个字节的
qingyuan18 2004-10-13
  • 打赏
  • 举报
回复
楼上的都好强啊!!
happyjun2000 2004-10-13
  • 打赏
  • 举报
回复
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Web.Security;

namespace Paladin.Common
{
/// <summary>
/// Security 的摘要说明。
/// 对称加密算法 : DES / TripleDES / RC2 / Rijndael
/// 非对称加密算法 : DSA / RSA
/// Base64 算法
/// </summary>
public class Cryptography
{
public Cryptography()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
// DES 的加密方法 。
// 私钥加密 / 对称算法 。
public static string Encrypt_Des( string cleanString )
{
//.NET 框架提供的对称加密类需要一个密钥和一个新的 IV 来加密和解密数据。
//每当使用默认的构造函数创建其中一个托管对称加密类的新实例时,就会自动创建新的密钥和 IV
//DES 使用 64 位密钥、64 位块来加密和解密数据。每个数据块迭代 16 次以生成加密文本。
//初始化向量(IV) 用来第一次对数据块进行加密 。
byte[] KEY_64 = {42, 16, 93, 156, 78, 4, 218, 32}; // 指定的 Key
byte[] IV_64 = {55, 103, 246, 79, 36, 99, 167, 3}; // 初始化向量(IV)
DESCryptoServiceProvider provider = new DESCryptoServiceProvider ( ) ;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream( ms , provider.CreateEncryptor( KEY_64,IV_64 ) , CryptoStreamMode.Write ) ;
StreamWriter sw = new StreamWriter( cs ) ;
sw.Write( cleanString ) ;
sw.Flush( ) ;
cs.FlushFinalBlock( ) ;
ms.Flush( ) ;
return Convert.ToBase64String( ms.GetBuffer( ) , 0 , int.Parse( ( ms.Length.ToString ( ) ) ) ) ;
}

// DES 的解密方法 。
// 私钥加密 / 对称算法 。
public static string Decrypt_Des( string encryptedString )
{
byte[] KEY_64 = {42, 16, 93, 156, 78, 4, 218, 32};
byte[] IV_64 = {55, 103, 246, 79, 36, 99, 167, 3};
DESCryptoServiceProvider provider = new DESCryptoServiceProvider ( ) ;
byte[] buffer = Convert.FromBase64String( encryptedString ) ;
MemoryStream ms = new MemoryStream ( buffer ) ;
CryptoStream cs = new CryptoStream( ms,provider.CreateDecryptor( KEY_64,IV_64 ) , CryptoStreamMode.Read ) ;
StreamReader sr = new StreamReader( cs ) ;
return sr.ReadToEnd ( ) ;

}

// hash 加密
public static string Encrypt_Hash(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

return BitConverter.ToString(hashedBytes);
}

// sha1 的方式加密密码
public static String Encrypt_Sha1( String oriPassWrd )
{
String returnstr="";

returnstr = FormsAuthentication.HashPasswordForStoringInConfigFile( oriPassWrd , "sha1" );

return returnstr;

}

// DSA 的数字签名
// RSA 类似,不过RSA比DSA慢得多,但比DSA安全。RSA可以选择关键字的大小,越大越安全
public static byte[] DsaCrypto_SignData ( string content , ref string dsaXmlString )
{
//先要将字符串转换为字节数组,这与编码有关。
// String content = "this is a test.";
byte[] bytes = Encoding.ASCII.GetBytes( content );
//选择签名方式,有RSA和DSA
DSACryptoServiceProvider dsac = new DSACryptoServiceProvider();
byte[] sign = dsac.SignData( bytes );
//当前 Dsa 对象的 xml 表示字符串 。
dsaXmlString = dsac.ToXmlString( false ) ;
//sign便是出来的签名结果。
return sign ;
}

// DSA 的数字签名认证
public static void DsaCrypto_VerifyData (string content , byte[] sign , string dsaXmlString )
{
byte[] bytes = Encoding.ASCII.GetBytes( content );
//下面是认证了
// DSACryptoServiceProvider dsac2 = new DSACryptoServiceProvider();
// dsac2.FromXmlString( dsac.ToXmlString( false ) );
// bool _verify = dsac2.VerifyData( bytes, sign );
DSACryptoServiceProvider dsac = new DSACryptoServiceProvider();
dsac.FromXmlString( dsaXmlString );
bool _verify = dsac.VerifyData( bytes, sign );
if ( _verify )
{
common.setMessage ( "通过" ) ;
}
else
{
common.setMessage ( "不能通过" ) ;
}
}
}//class
}
happyjun2000 2004-10-13
  • 打赏
  • 举报
回复
using System;
using System.Text;
using System.Runtime.InteropServices;

//namespace PetShop.Utility {
namespace Paladin.Common {
public enum Store {Machine = 1, User};

/// <summary>
/// The DSAPI wrapper
/// To be released as part of the Microsoft Configuration Building Block
/// 不能加密中文
/// </summary>
public class DataProtector {
#region Constants
static private IntPtr NullPtr = ((IntPtr)((int)(0)));
private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;
private Store store;
#endregion

#region P/Invoke structures
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct DATA_BLOB {
public int cbData;
public IntPtr pbData;
}

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct CRYPTPROTECT_PROMPTSTRUCT {
public int cbSize;
public int dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
#endregion

#region External methods
[DllImport("Crypt32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);

[DllImport("Crypt32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags,
ref IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
ref String lpBuffer,
int nSize,
IntPtr *Arguments);
#endregion

#region Constructor
public DataProtector(Store tempStore) {
store = tempStore;
}
#endregion

#region Public methods
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy) {
bool retVal = false;

DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherTextBlob = new DATA_BLOB();
DATA_BLOB entropyBlob = new DATA_BLOB();

CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);

int dwFlags;
try {
try {
int bytesSize = plainText.Length;
plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if(IntPtr.Zero == plainTextBlob.pbData) {
throw new Exception("Unable to allocate plaintext buffer.");
}
plainTextBlob.cbData = bytesSize;
Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize);
}
catch(Exception ex) {
throw new Exception("Exception marshalling data. " + ex.Message);
}
if(Store.Machine == store) {
//Using the machine store, should be providing entropy.
dwFlags = CRYPTPROTECT_LOCAL_MACHINE|CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if(null == optionalEntropy) {
//Allocate something
optionalEntropy = new byte[0];
}
try {
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length);
if(IntPtr.Zero == entropyBlob.pbData) {
throw new Exception("Unable to allocate entropy data buffer.");
}
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
entropyBlob.cbData = bytesSize;
}
catch(Exception ex) {
throw new Exception("Exception entropy marshalling data. " + ex.Message);
}
}
else {
//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptProtectData( ref plainTextBlob, "", ref entropyBlob,
IntPtr.Zero, ref prompt, dwFlags, ref cipherTextBlob);
if(false == retVal) {
throw new Exception("Encryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error()));
}
}
catch(Exception ex) {
throw new Exception("Exception encrypting. " + ex.Message);
}
byte[] cipherText = new byte[cipherTextBlob.cbData];
Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData);
return cipherText;
}

public byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy) {
bool retVal = false;
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherBlob = new DATA_BLOB();
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);
try {
try {
int cipherTextSize = cipherText.Length;
cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize);
if(IntPtr.Zero == cipherBlob.pbData) {
throw new Exception("Unable to allocate cipherText buffer.");
}
cipherBlob.cbData = cipherTextSize;
Marshal.Copy(cipherText, 0, cipherBlob.pbData, cipherBlob.cbData);
}
catch(Exception ex) {
throw new Exception("Exception marshalling data. " + ex.Message);
}
DATA_BLOB entropyBlob = new DATA_BLOB();
int dwFlags;
if(Store.Machine == store) {
//Using the machine store, should be providing entropy.
dwFlags = CRYPTPROTECT_LOCAL_MACHINE|CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if(null == optionalEntropy) {
//Allocate something
optionalEntropy = new byte[0];
}
try {
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if(IntPtr.Zero == entropyBlob.pbData) {
throw new Exception("Unable to allocate entropy buffer.");
}
entropyBlob.cbData = bytesSize;
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
}
catch(Exception ex) {
throw new Exception("Exception entropy marshalling data. " + ex.Message);
}
}
else {
//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptUnprotectData(ref cipherBlob, null, ref
entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref plainTextBlob);
if(false == retVal) {
throw new Exception("Decryption failed. " + GetErrorMessage(Marshal.GetLastWin32Error()));
}
//Free the blob and entropy.
if(IntPtr.Zero != cipherBlob.pbData) {
Marshal.FreeHGlobal(cipherBlob.pbData);
}
if(IntPtr.Zero != entropyBlob.pbData) {
Marshal.FreeHGlobal(entropyBlob.pbData);
}
}
catch(Exception ex) {
throw new Exception("Exception decrypting. " + ex.Message);
}
byte[] plainText = new byte[plainTextBlob.cbData];
Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData);
return plainText;
}
#endregion

#region Private methods
private void InitPromptstruct(ref CRYPTPROTECT_PROMPTSTRUCT ps) {
ps.cbSize = Marshal.SizeOf(typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags = 0;
ps.hwndApp = NullPtr;
ps.szPrompt = null;
}

private unsafe static String GetErrorMessage(int errorCode) {
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
IntPtr ptrlpSource = new IntPtr();
IntPtr prtArguments = new IntPtr();
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0,
ref lpMsgBuf, messageSize, &prtArguments);
if(0 == retVal) {
throw new Exception("Failed to format message for error code " + errorCode + ". ");
}
return lpMsgBuf;
}
#endregion

}
}




The123 2004-10-13
  • 打赏
  • 举报
回复
作者来了,分给他。
The123 2004-10-13
  • 打赏
  • 举报
回复
http://blog.csdn.net/kangsoft/archive/2004/09/06/96225.aspx

110,579

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧