我用Python编写了一个加密函数,运行良好。在
from cryptography.fernet import Fernet
def Encryptor(password):
key = b'MAKV2SPBNI99212'
cipher_suite = Fernet(key)
ciphered_text = cipher_suite.encrypt(password)
print(ciphered_text)
这个很好用
例如
^{pr2}$返回下面的输出
b'gaaaabbiwgjt5gezocezkowpmnxk_sntgoe9kluquoktnbpo1jfl87pxzai-CtCF2eXHfgZ0F5iPCV-qn2wrhhewwg6ehjw=='
我如何在C中解密这个。我不想在Python中使用Pycrypto
这是我用C语言尝试的代码,但是它不能工作,因为IV需要16个字节
public static string Decrypt()
{
byte[] someone = Encoding.UTF8.GetBytes("gAAAAABbIWGJt5gEZoCezKoWpMNxNk_SNTGoe9KlUoquktNbpo1JFL87PxZAi-CtCF2eXHfgZ0F5iPCV-qn2wRhheWfWG6eHJw==");
byte[] keybytes = Convert.FromBase64String("MAKV2SPBNI99212");
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keybytes, someone);
byte[] cipherTextBytes = Convert.FromBase64String("gAAAAABbIWGJt5gEZoCezKoWpMNxNk_SNTGoe9KlUoquktNbpo1JFL87PxZAi-CtCF2eXHfgZ0F5iPCV-qn2wRhheWfWG6eHJw==");
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
你的钥匙有问题。它太短了。为Fernet加密/解密编写了一些代码(这是非常基本的,不是基于流的),用找到的测试向量at a javascript implementation of Fernet进行测试。Fernet算法的规范可以找到here。请注意,您不能直接使用
Convert.FromBase64String
,因为Fernet使用的格式是Base64 url安全的。我用了一个小方法来转换它。在相关问题 更多 >
编程相关推荐