gpt4 book ai didi

c# - C# 中的 Des 和 3Des 以及 ecb(来自 C)

转载 作者:行者123 更新时间:2023-11-30 19:42:03 28 4
gpt4 key购买 nike

我有这段 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);
}

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

最佳答案

为什么不直接使用 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()

关于c# - C# 中的 Des 和 3Des 以及 ecb(来自 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32882406/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com