PHP Генерация токена до C#. Net - PullRequest
0 голосов
/ 19 марта 2020

Я пытаюсь преобразовать код двустороннего шифрования php basi c в код C#. Код php можно проверить на этом сайте -> https://www.the-art-of-web.com/php/two-way-encryption/. Я не уверен, что генерация IV в моем c# коде верна или нет. Токен, который я получил от C# и PHP, имеет тот же формат, но токен C# показывает недействительный. Пожалуйста, проверьте мой C# код, который мне нужно изменить.

PHP КОД:

 <?php
        $encrypted ="";
        function encryptToken($token)
        {  
            $cipher_method = 'aes-128-ctr';  
            $enc_key = openssl_digest('**********************', 'SHA256', TRUE);  
            $enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method)); 
             $crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . 
              bin2hex($enc_iv); 
              unset($token, $cipher_method, $enc_key, $enc_iv);  
              return $crypted_token; 
         }  
        function createAccessToken(){ 

         $now = date("YmdHis");
         $secret = '###################';  
         $plainText = $now."::".$secret;  
         $encrypted = encryptToken($plainText);  
         return $encrypted; 
        } 

        $encrypted = createAccessToken();
    ?>

C# КОД

        public string GenerateToken()
        {
            var Date = DateTime.Now.ToString("yyyyMMddHHmmss");
            var secret = "#############################";
            string plainText = Date + "::" + secret;
            var accessToken = EncryptString(plainText);
            return accessToken;
        }


public string EncryptString(string plainText)
    {
        try
        {
            string password = "************************";
            // Create sha256 hash
            SHA256 mySHA256 = SHA256Managed.Create();
            byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
            // Instantiate a new Aes object to perform string symmetric encryption
            Aes encryptor = Aes.Create();
            encryptor.Mode = CipherMode.ECB;
            encryptor.Padding = PaddingMode.None;
            encryptor.BlockSize = 128;
            // Create secret IV
            var iv = generateIV();
            // 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) + "::" + ByteArrayToString(iv);

            // Return the encrypted data as a string
            return cipherText;
        }
        catch (Exception)
        {

            throw;
        }
    }
    private static byte[] generateIV()
    {
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            byte[] nonce = new byte[IV_LENGTH];
            rng.GetBytes(nonce);
            return nonce;
        }
    }

Полученные токены

 PHP Token
 s9kMVUTBLvvjDJNean2kYyEHisYsEQHLQ54+7wV1zHdV1jRsSBFc6PNU0lyZ48VoCjckpm94xEgxKpTRCCXEX8CS/7PYbxZqNBFIZBtZZ3mXnkfA4rvkVEc6XuNXqLGdU3dFxbtWhikAMkHiiUPnPP5hR9UCyj2mAzJqHAwQ1Cn5VkyYWwJEHeyzQR4cwBVr::2e7d77b69ab1185e3d44af142aa6f358

C# token

qFSf2qQ+UHcqAoGUxj43wTO9fLhxfhwf+hYiRKq12amdcICJ6swXvSlV4P1/VYQm6ezNqF+x6LkjMfsxgG1Oyo71+T+mtSs0j5Bmu7eaZr5bDgAMMnZ8WrDKde2fGOgB81Gkj67L/Ka+dT+Ki0j/zsXMN454vqCzdUl0pw91TpwB8UHYni7sMA8JyLgto3Q4::418c68da838e2be51b0e84def5266024
...