- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
2013 年 3 月 24 日:
在转换为 utf-16 并在命中任何“e”或“m”字节之前停止之后,我的 Python 输出散列现在与 c++ 的散列相匹配。但是解密结果不匹配。我知道我的 SHA1 散列是 20 字节 = 160 位,而 RC4 key 的长度可以从 40 到 2048 位不等,所以我可能需要模仿 WinCrypt 中正在进行的一些默认加盐。 CryptGetKeyParam KP_LENGTH 或 KP_SALT
2013 年 3 月 24 日:
CryptGetKeyParam KP_LENGTH 告诉我我的 key 长度是 128 位。我正在为它提供 160 位哈希值。所以也许它只是丢弃了最后 32 位……或 4 个字节。立即测试。
2013 年 3 月 24 日:是的,就是这样。如果我在 python 中丢弃我的 SHA1 哈希的最后 4 个字节......我得到相同的解密结果。
我有一个 C++ 程序来解密数据 block 。它使用 Windows Crytographic Service Provider,因此只能在 Windows 上运行。我希望它能与其他平台一起使用。
在 Windows 加密 API 中 字节的 ASCII 编码密码被转换为宽字符表示,然后使用 SHA1 进行散列以生成 RC4 流密码的 key 。
Python 中的 PyCrypto ASCII 编码的字节字符串被解码为 python 字符串。它根据经验观察到的字节被截断,这导致 mbctowcs 在 C++ 中停止转换。然后将这个截断的字符串编码为 utf-16,有效地在字符之间填充 0x00 字节。这个新的截断、填充的字节字符串被传递给 SHA1 哈希,摘要的前 128 位被传递给 PyCrypto RC4 对象。
问题 [已解决]
我似乎无法使用带有 PyCrypto 的 Python 3.x 获得相同的结果
C++ 代码框架:
HCRYPTPROV hProv = 0x00;
HCRYPTHASH hHash = 0x00;
HCRYPTKEY hKey = 0x00;
wchar_t sBuf[256] = {0};
CryptAcquireContextW(&hProv, L"FileContainer", L"Microsoft Enhanced RSA and AES Cryptographic Provider", 0x18u, 0);
CryptCreateHash(hProv, 0x8004u, 0, 0, &hHash);
//0x8004u is SHA1 flag
int len = mbstowcs(sBuf, iRec->desc, sizeof(sBuf));
//iRec is my "Record" class
//iRec->desc is 33 bytes within header of my encrypted file
//this will be used to create the hash key. (So this is the password)
CryptHashData(hHash, (const BYTE*)sBuf, len, 0);
CryptDeriveKey(hProv, 0x6801, hHash, 0, &hKey);
DWORD dataLen = iRec->compLen;
//iRec->compLen is the length of encrypted datablock
//it's also compressed that's why it's called compLen
CryptDecrypt(hKey, 0, 0, 0, (BYTE*)iRec->decrypt, &dataLen);
// iRec is my record that i'm decrypting
// iRec->decrypt is where I store the decrypted data
//&dataLen is how long the encrypted data block is.
//I get this from file header info
Python 代码框架:
from Crypto.Cipher import ARC4
from Crypto.Hash import SHA
#this is the Decipher method from my record class
def Decipher(self):
#get string representation of 33byte password
key_string= self.desc.decode('ASCII')
#so far, these characters fail, possibly others but
#for now I will make it a list
stop_chars = ['e','m']
#slice off anything beyond where mbstowcs will stop
for char in stop_chars:
wc_stop = key_string.find(char)
if wc_stop != -1:
#slice operation
key_string = key_string[:wc_stop]
#make "wide character"
#this is equivalent to padding bytes with 0x00
#Slice off the two byte "Byte Order Mark" 0xff 0xfe
wc_byte_string = key_string.encode('utf-16')[2:]
#slice off the trailing 0x00
wc_byte_string = wc_byte_string[:len(wc_byte_string)-1]
#hash the "wchar" byte string
#this is the equivalent to sBuf in c++ code above
#as determined by writing sBuf to file in tests
my_key = SHA.new(wc_byte_string).digest()
#create a PyCrypto cipher object
RC4_Cipher = ARC4.new(my_key[:16])
#store the decrypted data..these results NOW MATCH
self.decrypt = RC4_Cipher.decrypt(self.datablock)
怀疑[编辑:确认]原因
1. 密码的 mbstowcs 转换导致被馈送到 SHA1 哈希的“原始数据”在 python 和 c++ 中是不一样的。 mbstowcs 在 0x65 和 0x6D 字节处停止转换。原始数据仅以原始 33 字节密码的一部分的 wide_char 编码结尾。
我是如何调查的编辑:根据我自己的实验和@RolandSmith 的建议,我现在知道我的问题之一是 mbctowcs 的行为方式出乎我的意料。它似乎停止在“e”(0x65)和“m”(0x6d)(可能是其他)上写入 sBuf。因此,我的描述中的密码“Monkey”(Ascii 编码字节)在 sBuf 中看起来像“M o n k”,因为 mbstowcs 在 e 处停止,并根据我系统上的 2 字节 wchar typedef 在字节之间放置 0x00。我通过将转换结果写入文本文件找到了这一点。
BYTE pbHash[256]; //buffer we will store the hash digest in
DWORD dwHashLen; //store the length of the hash
DWORD dwCount;
dwCount = sizeof(DWORD); //how big is a dword on this system?
//see above "len" is the return value from mbstowcs that tells how
//many multibyte characters were converted from the original
//iRec->desc an placed into sBuf. In some cases it's 3, 7, 9
//and always seems to stop on "e" or "m"
fstream outFile4("C:/desc_mbstowcs.txt", ios::out | ios::trunc | ios::binary);
outFile4.write((const CHAR*)sBuf, int(len));
outFile4.close();
//now get the hash size from CryptGetHashParam
//an get the acutal hash from the hash object hHash
//write it to a file.
if(CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&dwHashLen, &dwCount, 0)) {
if(CryptGetHashParam(hHash, 0x0002, pbHash, &dwHashLen,0)){
fstream outFile3("C:/test_hash.txt", ios::out | ios::trunc | ios::binary);
outFile3.write((const CHAR*)pbHash, int(dwHashLen));
outFile3.close();
}
}
引用资料:
宽字符会导致问题,具体取决于环境定义
Difference in Windows Cryptography Service between VC++ 6.0 and VS 2008
将 utf-8 字符串转换为 utf-16 字符串
Python - converting wide-char strings from a binary file to Python unicode strings
PyCrypto RC4 示例
https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.ARC4-module.html
http://msdn.microsoft.com/en-us/library/windows/desktop/aa379916(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa375599(v=vs.85).aspx
最佳答案
您可以使用一个小测试程序(C 语言)测试wchar_t
的大小:
#include <stdio.h> /* for printf */
#include <stddef.h> /* for wchar_t */
int main(int argc, char *argv[]) {
printf("The size of wchar_t is %ld bytes.\n", sizeof(wchar_t));
return 0;
}
您还可以在 C++ 代码中使用 printf()
调用来编写例如iRec->desc
和 sbuf
中的散列结果显示在屏幕上(如果您可以从终端运行 C++ 程序)。否则使用 fprintf()
将它们转储到文件中。
为了更好地模仿 C++ 程序的行为,您甚至可以使用 ctypes
在您的 Python 代码中调用 mbstowcs()
。
编辑:您写道:
One problem is definitely with mbctowcs. It seems that it's transferring an unpredictable (to me) number of bytes into my buffer to be hashed.
请记住,mbctowcs
返回转换后的宽字符数。换句话说,多字节编码中的 33 字节缓冲区可以包含从 5(UTF-8 6 字节序列)到 33 个字符的任何内容,具体取决于所使用的编码。
Edit2:您正在使用 0 作为 CryptDeriveKey
的 dwFlags
参数。根据其documentation ,高 16 位应包含 key 长度。您应该检查 CryptDeriveKey
的返回值以查看调用是否成功。
Edit3:您可以在 Python 中测试 mbctowcs
(我在这里使用 IPython。):
In [1]: from ctypes import *
In [2]: libc = CDLL('libc.so.7')
In [3]: monkey = c_char_p(u'Monkey')
In [4]: test = c_char_p(u'This is a test')
In [5]: wo = create_unicode_buffer(256)
In [6]: nref = c_size_t(250)
In [7]: libc.mbstowcs(wo, monkey, nref)
Out[7]: 6
In [8]: print wo.value
Monkey
In [9]: libc.mbstowcs(wo, test, nref)
Out[9]: 14
In [10]: print wo.value
This is a test
请注意,在 Windows 中,您可能应该使用 libc = cdll.msvcrt
而不是 libc = CDLL('libc.so.7')
。
关于c++ - 重复的 Windows 加密服务提供程序导致 Python w/Pycrypto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537775/
我正在尝试使用 Spark 从 Cassandra 读取数据。 DataFrame rdf = sqlContext.read().option("keyspace", "readypulse
这是代码: void i_log_ (int error, const char * file, int line, const char * fmt, ...) { /* Get erro
我必须调试一个严重依赖 Gtk 的程序。问题是由于某些原因,在使用 GtkWindow 对象时开始出现许多运行时警告。问题是,即使 Gtk 提示严重错误,它也不会因这些错误而中止。我没有代码库的更改历
我正在尝试从已有效编译和链接的程序中检索二进制文件。我已经通过 GL_PROGRAM_BINARY_LENGTH 收到了它的长度。该文档说有两个实例可能会发生 GL_INVALID_OPERATION
我有一个托管在 Azure 环境中的服务。我正在使用控制台应用程序使用该服务。这样做时,我得到了异常: "The requested service, 'http://xxxx-d.yyyy.be/S
我有以下代码,它被 SEGV 信号杀死。使用调试器表明它被 main() 中的第一个 sem_init() 杀死。如果我注释掉第一个 sem_init() ,第二个会导致同样的问题。我试图弄清楚是什么
目前我正在编写一个应用程序(目标 iOS 6,启用 ARC),它使用 JSON 进行数据传输,使用核心数据进行持久存储。 JSON 数据由 PHP 脚本通过 json_encode 从 MySQL 数
我对 Xamarin.Forms 还是很陌生。我在出现的主页上有一个非常简单的功能 async public Task BaseAppearing() { if (UserID
这是我的代码的简化版本。 public class MainActivity extends ActionBarActivity { private ArrayList entry = new Arr
我想弄明白为什么我的两个 Java 库很难很好地协同工作。这是场景: 库 1 有一个类 A,其构造函数如下: public A(Object obj) { /* boilerplate */ } 在以
如果网站不需要身份验证,我的代码可以正常工作,如果需要,则在打印“已创建凭据”后会立即出现 EXC_BAD_ACCESS 错误。我不会发布任何内容,并且此代码是直接从文档中复制的 - 知道出了什么问题
我在使用 NSArray 填充 UITableView 时遇到问题。我确信我正在做一些愚蠢的事情,但我无法弄清楚。当我尝试进行简单的计数时,我得到了 EXC_BAD_ACCESS,我知道这是因为我试图
我在 UITableViewCell 上有一个 UITextField,在另一个单元格上有一个按钮。 我单击 UITextField(出现键盘)。 UITextField 调用了以下方法: - (BO
我有一个应用程序出现间歇性崩溃。崩溃日志显示了一个堆栈跟踪,这对我来说很难破译,因此希望其他人看到了这一点并能为我指出正确的方向。 基本上,应用程序在启动时执行反向地理编码请求,以在标签中显示用户的位
我开发了一个 CGImage,当程序使用以下命令将其显示在屏幕上时它工作正常: [output_view.layer performSelectorOnMainThread:@selector(set
我正在使用新的 EncryptedSharedPreferences以谷歌推荐的方式上课: private fun securePrefs(context: Context): SharedPrefe
我有一个中继器,里面有一些控件,其中一个是文本框。我正在尝试使用 jquery 获取文本框,我的代码如下所示: $("#").click(function (event) {}); 但我总是得到 nu
在以下场景中观察到 TTS 初始化错误,太随机了。 已安装 TTS 引擎,存在语音集,并且可以从辅助功能选项中播放示例 tts。 TTS 初始化在之前初始化和播放的同一设备上随机失败。 在不同的设备(
maven pom.xml org.openjdk.jol jol-core 0.10 Java 类: public class MyObjectData { pr
在不担心冲突的情况下,可以使用 MD5 作为哈希值,字符串长度最多为多少? 这可能是通过为特定字符集中的每个可能的字符串生成 MD5 哈希来计算的,长度不断增加,直到哈希第二次出现(冲突)。没有冲突的
我是一名优秀的程序员,十分优秀!