ファイルI/Oを利用したテストベンチ / ハッシュ生成器

pp.555-556

今度はファイルI/Oを利用したテストベンチ。

↓ これが今回のDUV。任意の長さの文字列(ここでは32文字)に何らかの演算を適用して任意のビット数の数値(ここでは32ビット)に変換する。character'pos(文字)characterタイプに事前定義されている各文字の位置を返す。要するに文字コードを返す。

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity hash_calculator is
    port (
        message: in string(1 to 32);
        hash: out std_logic_vector(31 downto 0)
    );
end;

architecture rtl of hash_calculator is
begin
    process (message)
        variable h: std_logic_vector(31 downto 0);
        variable msg_byte: std_logic_vector(7 downto 0);
    begin
        h := (others => '0');
        for i in message'range loop
            msg_byte := std_logic_vector(to_unsigned(character'pos(message(i)), 8));
           --h := (h rol 4) xor (24x"0" & msg_byte);
            h := (h(27 downto 0) & h(31 downto 28)) xor (24x"0" & msg_byte);
        end loop;
        hash <= h;
    end process;
end;

Pythonで書き換えた。

def rotation_left(val, bits, width):
    return (val << bits | val >> width - bits) & (2**width - 1)

def calc_hash(message, width):
    h = 0
    for char in message:
        msg_byte = ord(char)
        h = rotation_left(h, 4, width) ^ msg_byte
    return h

message = "bjwvsqt1x9aot0orrt4eckp5srg61zhh"
hash_width = 32

print(bin(calc_hash(message, hash_width)))