【Unity】「DES」数据加密解密

71 篇文章 2 订阅
定义秘钥

        //加解密密钥,可自行替换
        protected static string tmpDESkey = "gBPZodCkn6T";
         // Create sha256 hash
        static SHA256 mySHA256 = SHA256Managed.Create();
        protected  static byte[] basekey = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(tmpDESkey));
        // Create secret IV
        protected static byte[] baseiv = new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
加密

        #region DESEnCode DES加密   
        public static string DESEnCode (string plainText)
        {
            byte[] key=basekey;
            byte[] iv=baseiv;
           
            Aes encryptor = Aes.Create();

            encryptor.Mode = CipherMode.CBC;

            // Set key and IV
            byte[] aesKey = new byte[32];
            Array.Copy(key, 0, aesKey, 0, 32);
            encryptor.Key = aesKey;
            encryptor.IV = iv;

            // Instantiate a new MemoryStream object to contain the encrypted bytes
            MemoryStream memoryStream = new MemoryStream();

            // Instantiate a new encryptor from our Aes object
            ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();

            // Instantiate a new CryptoStream object to process the data and write it to the 
            // memory stream
            CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

            // Convert the plainText string into a byte array
            byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);

            // Encrypt the input plaintext string
            cryptoStream.Write(plainBytes, 0, plainBytes.Length);

            // Complete the encryption process
            cryptoStream.FlushFinalBlock();

            // Convert the encrypted data from a MemoryStream to a byte array
            byte[] cipherBytes = memoryStream.ToArray();

            // Close both the MemoryStream and the CryptoStream
            memoryStream.Close();
            cryptoStream.Close();

            // Convert the encrypted byte array to a base64 encoded string
            string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

            // Return the encrypted data as a string
             return cipherText;

        }
        #endregion
解密

        #region DESDeCode DES解密
        //public static  string DESDeCode(string pToDecrypt, string sKey)
        public static string DESDeCode(string cipherText)
        {
            byte[] key=basekey;
            byte[] iv=baseiv;
            
            // Instantiate a new Aes object to perform string symmetric encryption
            Aes encryptor = Aes.Create();

            encryptor.Mode = CipherMode.CBC;

            // Set key and IV
            byte[] aesKey = new byte[32];
            Array.Copy(key, 0, aesKey, 0, 32);
            encryptor.Key = aesKey;
            encryptor.IV = iv;

            // Instantiate a new MemoryStream object to contain the encrypted bytes
            MemoryStream memoryStream = new MemoryStream();

            // Instantiate a new encryptor from our Aes object
            ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();

            // Instantiate a new CryptoStream object to process the data and write it to the 
            // memory stream
            CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

            // Will contain decrypted plaintext
            string plainText = String.Empty;

            try
            {
                // Convert the ciphertext string into a byte array
                byte[] cipherBytes = Convert.FromBase64String(cipherText);

                // Decrypt the input ciphertext string
                cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

                // Complete the decryption process
                cryptoStream.FlushFinalBlock();

                // Convert the decrypted data from a MemoryStream to a byte array
                byte[] plainBytes = memoryStream.ToArray();

                // Convert the decrypted byte array to string
                plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
            }
            finally
            {
                // Close both the MemoryStream and the CryptoStream
                memoryStream.Close();
                cryptoStream.Close();
            }

            // Return the decrypted data as a string
            return plainText;
        }
        #endregion
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity中的WebSocket加密解密可以通过使用SSL/TLS协议来实现。具体来说,可以使用Unity的`SslStream`类来对WebSocket通信进行加密和解密。 在使用`SslStream`之前,需要先创建一个`TcpClient`对象来与WebSocket服务器建立连接。然后,可以使用`SslStream`的构造函数来创建一个加密的流对象。最后,可以使用`SslStream`的`Read()`和`Write()`方法来对WebSocket通信进行加密和解密。 以下是一个示例代码: ```csharp using System; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using UnityEngine; public class WebSocketClient : MonoBehaviour { private TcpClient tcpClient; private SslStream sslStream; private byte[] receiveBuffer = new byte[1024]; private async Task Connect(string serverIp, int serverPort) { tcpClient = new TcpClient(); await tcpClient.ConnectAsync(serverIp, serverPort); // Create SslStream object with client certificate validation sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); // Authenticate server and client with SSL/TLS connection try { await sslStream.AuthenticateAsClientAsync(serverIp); } catch (AuthenticationException e) { Debug.LogError($"SSL/TLS authentication failed: {e.Message}"); tcpClient.Close(); return; } // Start listening for incoming WebSocket messages await Receive(); } private async Task Receive() { // Read incoming data from WebSocket server int bytesReceived = await sslStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length); // Decrypt received data // Process decrypted data // Continue listening for incoming WebSocket messages await Receive(); } private void Send(string message) { // Encrypt outgoing data // Send encrypted data to WebSocket server byte[] sendBuffer = System.Text.Encoding.UTF8.GetBytes(message); sslStream.Write(sendBuffer, 0, sendBuffer.Length); } private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // Perform certificate validation if needed return true; } } ``` 请注意,以上代码仅提供了WebSocket加密解密的基本思路,具体实现可能因应用场景而有所不同。还需要根据实际情况进行一些改进,比如对接收到的数据进行解析和处理,对发送的数据进行封装和编码等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值