2012-04-18 33 views
0

我試圖做出簡單的庫布萊克哈希函數包裝使用從C的python ctypes。但僅用於測試在一開始是否我簡單的C幫助函數可以正常工作,我寫了一個小型的python腳本blake hash函數測試向量。我的問題出現在這個小小的劇本中。我在幾個小時就磕磕絆絆來解決這個問題。我通過使用這個小助手測試向量腳本總是得到了意想不到的「blake 512 usage」的64個字節的輸出值。我意識到,我的問題來自於我在嘗試返回(而且應該是確切的)64字節的時候編寫的c幫助器函數,以後將使用這個小型python ctypes腳本測試向量。包裝布萊克哈希函數C實現到Python使用ctypes模塊,簡單的python ctypes testvector腳本也包括

我使用的純C實現源直接從NIST Blake的Optimizedized 32位處理器提交下載,文件名爲blake_opt32.c和blake_opt32.h。可以在這裏下載http://csrc.nist.gov/groups/ST/hash/sha-3/Round3/documents/Blake_FinalRnd.zip

這裏是我的簡單的C幫助函數,以供以後通過使用python ctypes調用。

#include <stdio.h> 
#include "blake_opt32.h" 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <string.h> 
#include <stdint.h> 

BitSequence msg[65]; 

size_t strlcpy(unsigned char *dst, const char *src, size_t siz) 
{ 
unsigned char *d = dst; 
const char *s = src; 
size_t n = siz; 

/* Copy as many bytes as will fit */ 
if (n != 0) { 
    while (--n != 0) { 
     if ((*d++ = *s++) == '\0') 
      break; 
    } 
} 

/* Not enough room in dst, add NUL and traverse rest of src */ 
if (n == 0) { 
    if (siz != 0) 
     *d = '\0';  /* NUL-terminate dst */ 
    while (*s++) 
     ; 
} 

return(s - src - 1); /* count does not include NUL */ 
} 

BitSequence * bl(char *input) 
{ 
BitSequence output[65]; 
BitSequence msg[sizeof(output)]; 
int dInt; 

memset(output,0,sizeof(output)); 
dInt = strlen(input); 

if (dInt > 0xffff){ 
    exit(1); 
} 
BitSequence data[dInt]; 

memset(data, 0, dInt); 
strlcpy(data, input, sizeof(data)); 
DataLength dLen =1152; 
Hash(512, data, dLen, output); 
int x; 
for (x=0;x<64;++x){ 
    printf("%02X",output[x]); 
} 
memcpy(msg,output,sizeof(output)); 
//here the problem araised, when trying to return unsigned char or BitSequence value, the unexpected output of small python scipt test vectors value is detected 
return msg; 
} 

而且簡單的小python腳本的測試向量是在這裏,只是輸出重定向到文件的任何文字,後來意外的值會被逮住試試這個小腳本。

from ctypes import * 
from string import printable 
from itertools import permutations 
from random import * 
d = CDLL('blake.dll') #edit here your own dll or .so library 
d.bl.restype = c_char_p 

print '[+] Simple Test-vectors Blake hash function\n' 
s = SystemRandom() 
for x in permutations(printable): 
p = ''.join(map(str,x)) 
q = list(p) 
s.shuffle(q) 
r= d.bl(''.join(map(str,q))) 
if ((len(r)*2) != 0x80): 
    print '\n[-] Not persistent value of 64 bytes was detected : %d'% len(r) 
    w = r.encode('hex') 
    print w, '-->', len(w) 
    print '\n' 
elif ((len(r)*2) == 0x80): 
    print '\n',len(r), '\n',r.encode('hex') 
    print '\n' 

因此,上面後,我的助手C函數中的任何更正使用爲了這個小Python腳本測試向量可以預料,將不勝感激的輸出值調用,非常面前謝謝! 順便提一下,是一個更新的代碼。

回答

0

功能BitSequence * bl(char *input)結束時,返回值output是一個局部變量,該函數退出後將不會存在。

+0

那麼,返回值應該是全局變量嗎? – hafidh 2012-04-19 03:25:30

+0

僅從gcc警告消息中重新調用,但仍然使用上面的testvector,多次檢測到意外的值....? – hafidh 2012-04-19 04:15:29