【问题标题】:Des and 3Des with ecb in C# (from C)C# 中带有 ecb 的 Des 和 3Des(来自 C)
【发布时间】:2015-12-29 04:51:18
【问题描述】:

我有这个 C 代码,我必须用 C# 编写它。

如何在 C# 中编写这些 ecb des 和 3des 函数?

/**
* Simple Single-Des Encryption procedure.
* Does not modify the input data.
* Encrypted result is returned in a separate buffer.
*
* @param pResult    (out) Result of the encrypted byte
* @param pData      (in)  One byte of input data
* @param pKey       (in)  The DES-key
*/

void DesEncrypt(void *pResult, const void *pData, KEY_1DES *pKey)
{
    memcpy(pResult, pData, 8);
    DES_key_schedule k;
    DES_set_key_unchecked((const_DES_cblock *)&pKey, &k);
    DES_ecb_encrypt((const_DES_cblock *)pData, (const_DES_cblock *)pResult, &k, DES_ENCRYPT);
}


/**
* Encrypts a byte using double length 3DES
*
* @param pResult    (out) Result of the decryption
* @param pData      (in)  One byte of input data
* @param pKey       (in)  The 3DES-key
*/

void DesEncrypt3Des(void *pResult, const void *pData, KEY_3DES *pKey)
{
    memcpy(pResult, pData, 8);
    //DES_set_key_checked()
    DES_key_schedule left;
    DES_set_key_unchecked((const_DES_cblock *)&pKey->left, &left);
    DES_key_schedule right;
    DES_set_key_unchecked((const_DES_cblock *)&pKey->right, &right);
    DES_ecb3_encrypt((const_DES_cblock *)pData, (const_DES_cblock *)pResult, &left, &right, &left, DES_ENCRYPT);
}

我问这个是因为有很多方法可以做到这一点,我必须确保使用相同的加密参数。

【问题讨论】:

    标签: c# c converter des 3des


    【解决方案1】:

    你为什么不直接使用System.Security.Cryptography中的TripleDESCryptoServiceProvider?

    public static string Encrypt(string data, string pKey)
    {
        TripleDESCryptoServiceProvider cryptor = new TripleDESCryptoServiceProvider();
        byte[] array = null;
        cryptor.Key = pKey;
        cryptor.Mode = CipherMode.ECB;
        ICryptoTransform encrypt = cryptor.CreateEncryptor();
        array = ASCIIEncoding.ASCII.GetBytes(data);
        string retVal = "";
        retVal = Convert.ToBase64String(encrypt.TransformFinalBlock(array, 0, array.Length));
        return retVal;
    }
    

    解密使用相同的逻辑,但调用CreateDecryptor()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2016-12-22
      相关资源
      最近更新 更多