首页>>帮助中心>>美国vps服务器C#中字符串加密和解密技术怎么实现

美国vps服务器C#中字符串加密和解密技术怎么实现

2024/4/29 413次

美国vps服务器C#中,可以使用一些加密算法来实现字符串加密和解密。常用的加密算法包括对称加密算法(如AESDESRC4等)和非对称加密算法(如RSA)。

下面是一个简单示例,演示如何使用AES算法进行字符串加密和解密:

using System;

using System.Security.Cryptography;

using System.Text;

public class AesEncryption

{

private static readonly byte[] key = Encoding.UTF8.GetBytes("encryptionkey123"); // 16 bytes key for AES

private static readonly byte[] iv = Encoding.UTF8.GetBytes("encryptioniv456"); // 16 bytes IV for AES

public static string EncryptString(string plainText)

{

using (Aes aesAlg = Aes.Create())

{

aesAlg.Key = key;

aesAlg.IV = iv;

ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

byte[] encrypted;

using (var msEncrypt = new System.IO.MemoryStream())

{

using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

{

using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))

{

swEncrypt.Write(plainText);

}

encrypted = msEncrypt.ToArray();

}

}

return Convert.ToBase64String(encrypted);

}

}

public static string DecryptString(string cipherText)

{

byte[] cipherBytes = Convert.FromBase64String(cipherText);

using (Aes aesAlg = Aes.Create())

{

aesAlg.Key = key;

aesAlg.IV = iv;

ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

string plaintext = null;

using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))

{

using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

{

using (var srDecrypt = new System.IO.StreamReader(csDecrypt))

{

plaintext = srDecrypt.ReadToEnd();

}

}

}

return plaintext;

}

}

public static void Main()

{

string original = "Hello, world!";

string encrypted = EncryptString(original);

string decrypted = DecryptString(encrypted);

Console.WriteLine("Original: {0}", original);

Console.WriteLine("Encrypted: {0}", encrypted);

Console.WriteLine("Decrypted: {0}", decrypted);

}

}

复制代码

在上面的示例中,我们使用了AES算法来加密和解密字符串。首先,我们需要定义一个16字节的密钥和初始向量IV,然后使用这些参数创建一个Aes实例。接着,我们使用CreateEncryptor方法创建一个加密器,并使用CreateDecryptor方法创建一个解密器。最后,我们可以分别使用加密器和解密器来加密和解密字符串。

购买使用一诺网络美国VPS,可以极大降低初创企业、中小企业以及个人开发者等用户群体的整体IT使用成本,无需亲自搭建基础设施、简化了运维和管理的日常工作量,使用户能够更专注于自身的业务发展和创新。美国VPS低至49/月,购买链接:https://www.enuoidc.com/vpszq.html?typeid=3