要在C#和Node.js中互相实现DES加密和解密,可以使用相同的算法和密钥来进行操作。下面是一个示例:
C#中的DES加密解密示例:
using System;using System.Security.Cryptography;using System.Text;public class Program{ public static void Main() { string originalText = "Hello, world!"; string key = "mySecretKey"; byte[] encryptedBytes = Encrypt(originalText, key); string encryptedText = Convert.ToBase64String(encryptedBytes); Console.WriteLine("Encrypted text: " + encryptedText); string decryptedText = Decrypt(encryptedBytes, key); Console.WriteLine("Decrypted text: " + decryptedText); } public static byte[] Encrypt(string plainText, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = keyBytes; des.IV = keyBytes; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); return memoryStream.ToArray(); } } } } public static string Decrypt(byte[] encryptedBytes, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = keyBytes; des.IV = keyBytes; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length); cryptoStream.FlushFinalBlock(); return Encoding.UTF8.GetString(memoryStream.ToArray()); } } } } }
Node.js中的DES加密解密示例:
const crypto = require('crypto');function encrypt(plainText, key) { const cipher = crypto.createCipheriv('des', key, key); let encrypted = cipher.update(plainText, 'utf8', 'base64'); encrypted += cipher.final('base64'); return encrypted; }function decrypt(encryptedText, key) { const decipher = crypto.createDecipheriv('des', key, key); let decrypted = decipher.update(encryptedText, 'base64', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; }const originalText = 'Hello, world!';const key = 'mySecretKey';const encryptedText = encrypt(originalText, key);console.log('Encrypted text:', encryptedText);const decryptedText = decrypt(encryptedText, key);console.log('Decrypted text:', decryptedText);
请注意,这只是一个基本的示例,用于演示如何在C#和Node.js中使用DES算法进行加密和解密。在实际应用中,应考虑更多的安全性和最佳实践,例如密钥管理、加密模式和填充方式的选择等。
希望以上解答对你有帮助。如果你有任何其他问题,请随时提问。