2012-03-13 68 views
1

我正在爲Vala和Linux寫一個跨平臺的應用程序。我需要實現Hmac的安全性;但不幸的是,GHmac類(link)尚未被移植到Windows。我在wikipedia上找到了Hmac的算法(link),我相信我正確實現了它,但是與內置類相比,我沒有得到相同的結果。如果任何人都可以幫我找到一個令人驚歎的bug,那麼下面是我的功能。在Vala中編寫Hmac函數

public static string compute_for_data(ChecksumType type, uint8[] key, 
                  uint8[] data) { 
    int block_size = 64; 
    uint8[] mod_key = key; 
    uint8[] outer = new uint8[block_size]; 
    uint8[] inner = new uint8[block_size]; 

    if (mod_key.length > block_size) { 
     mod_key = Checksum.compute_for_data(type, key).data; 
    } 
    mod_key.resize(block_size); 

    for (int i=0; i < mod_key.length; i++) { 
     outer[i] = mod_key[i]^0x5c; 
     inner[i] = mod_key[i]^0x36; 
    } 

    int i = inner.length; 
    inner.resize(i + data.length); 
    for (int j=0; j < data.length; j++) { 
     inner[i + j] = data[j]; 
    } 

    inner = Checksum.compute_for_data(type, inner).data; 

    i = outer.length; 
    outer.resize(i + inner.length); 
    for (int j=0; j < inner.length; j++) { 
     outer[i + j] = inner[j]; 
    } 

    return Checksum.compute_for_data(type, outer); 
} 

回答

2

我知道它的俗氣回答自己的問題,但我設法在朋友的幫助下解決它,所以這裏是解決方案。基本上,當我使用Checksum.compute_for_data函數時,它返回一個不是十六進制數據的十六進制字符串,並打破了算法。這是更正後的版本:

public static string compute_for_data(ChecksumType type, uint8[] key, 
                  uint8[] data) { 
    int block_size = 64; 
    switch (type) { 
     case ChecksumType.MD5: 
     case ChecksumType.SHA1: 
      block_size = 64; /* RFC 2104 */ 
      break; 
     case ChecksumType.SHA256: 
      block_size = 64; /* RFC draft-kelly-ipsec-ciph-sha2-01 */ 
      break; 
    } 

    uint8[] buffer = key; 
    if (key.length > block_size) { 
     buffer = Checksum.compute_for_data(type, key).data; 
    } 
    buffer.resize(block_size); 

    Checksum inner = new Checksum(type); 
    Checksum outer = new Checksum(type); 

    uint8[] padding = new uint8[block_size]; 
    for (int i=0; i < block_size; i++) { 
     padding[i] = 0x36^buffer[i]; 
    } 
    inner.update(padding, padding.length); 
    for (int i=0; i < block_size; i++) { 
     padding[i] = 0x5c^buffer[i]; 
    } 
    outer.update(padding, padding.length); 

    size_t length = buffer.length; 
    inner.update(data, data.length); 
    inner.get_digest(buffer, ref length); 

    outer.update(buffer, length); 
    return outer.get_string(); 
}