質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.47%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

665閲覧

pythonでのSHA256の実装

退会済みユーザー

退会済みユーザー

総合スコア0

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/06/17 09:36

下記のように、SHA256をpythonで書かれたスクリプトを実行したところ、エラーが表示されました。
なぜ、このようなエラーが表示されるのかを教えて頂けると幸いです。
python3.7を使用しており、python2との互換性の問題かとも思いましたが、自信では分かりませんでした。
よろしくお願いします。

python

1 2 3BLOCK_SIZE = 64 4DIGEST_SIZE = 32 5BITS_IN_WORD = 32 # w - Number of bits in a word. 6 7# SHA-224 and SHA-256 use the same sequence of sixty-four constant 32-bit words.These words represent 8# the first thirty-two bits of the fractional parts of the cube roots of the first sixty-four prime numbers. 9K256 = [ 10 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 11 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 12 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 13 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 14 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 15 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 16 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 17 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, 18] 19 20# Before hash computation begins for each of the secure hash algorithms, the initial hash value, 21# H(0), must be set. The size and number of words in H(0) depends on the message digest size. 22# For SHA-256, the initial hash value, H(0), shall consist of the following eight 32-bit words, in hex: 23INITIAL_HASH = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19] 24 25 26def shift_right(x, n): 27 """The right shift operation SHR n(x), where x is a w-bit word and n is an integer with 0 ≤ n < w, is defined by 28 SHR n (x)=x >> n. 29 """ 30 return (x & 0xffffffff) >> n 31 32 33def rotate_right(x, y): 34 """The rotate right (circular right shift) operation, where x is a w-bit word 35 and n is an integer with 0 ≤ n < w, is defined by ROTR n (x) =(x >> n) ∨ (x << w - n). 36 """ 37 return (((x & 0xffffffff) >> (y & 31)) | (x << (BITS_IN_WORD - (y & 31)))) & 0xffffffff 38 39 40""" 41SHA256 uses six logical functions, where each function operates on 64-bit words, 42which are represented as x, y, and z. The result of each function is a new 64-bit word. 43""" 44 45 46def choose(x, y, z): 47 """The x input chooses if the output is from y or z. 48 Ch(x,y,z)=(x∧y)⊕(¬x∧z) 49 """ 50 return z ^ (x & (y ^ z)) 51 52 53def majority(x, y, z): 54 """The result is set according to the majority of the 3 inputs. 55 Maj(x, y,z) = (x ∧ y) ⊕ (x ∧ z) ⊕ ( y ∧ z) 56 The functions are defined for bit vectors (of 32 bits in case fo SHA-256) 57 """ 58 return ((x | y) & z) | (x & y) 59 60 61def sigma0(x): 62 # ROTR 2(x) ⊕ ROTR 13(x) ⊕ ROTR 22(x) 63 return rotate_right(x, 2) ^ rotate_right(x, 13) ^ rotate_right(x, 22) 64 65 66def sigma1(x): 67 # ROTR 6(x) ⊕ ROTR 11(x) ⊕ ROTR 25(x) 68 return rotate_right(x, 6) ^ rotate_right(x, 11) ^ rotate_right(x, 25) 69 70 71def gamma0(x): 72 # ROTR 7(x) ⊕ ROTR 18(x) ⊕ SHR 3(x) 73 return rotate_right(x, 7) ^ rotate_right(x, 18) ^ shift_right(x, 3) 74 75 76def gamma1(x): 77 # ROTR 17(x) ⊕ ROTR 19(x) ⊕ SHR 10(x) 78 return rotate_right(x, 17) ^ rotate_right(x, 19) ^ shift_right(x, 10) 79 80 81def mutate(data, digest): 82 digest_copy = digest[:] 83 84 # 6.2.2: The SHA-256 hash computation uses functions and constants previously 85 # defined in Sec. 4.1.2 and Sec. 4.2.2, respectively. 86 # Addition (+) is performed modulo 232. 87 88 # Prepare the message schedule, {Wt}: 89 w = [] 90 for i in range(0, 16): 91 w.append(sum([ 92 data[4 * i + 0] << 24, 93 data[4 * i + 1] << 16, 94 data[4 * i + 2] << 8, 95 data[4 * i + 3] << 0, 96 ])) 97 98 for i in range(16, 64): 99 sum_ = gamma1(w[i - 2]) + w[i - 7] + gamma0(w[i - 15]) + w[i - 16] 100 w.append(sum_ & 0xffffffff) 101 102 for idx in xrange(0, -64, -1): 103 i = abs(idx % 8) 104 105 # Initialize the eight working variables, a, b, c, d, e, f, g, and h with the (i-1)st hash value. 106 # W is the prepared message schedule. 107 positions = [(i + x) % 8 for x in xrange(8)] 108 d_position = positions[3] 109 h_position = positions[-1] 110 a, b, c, d, e, f, g, h = [digest_copy[pos] for pos in positions] 111 112 t1 = h + sigma1(e) + choose(e, f, g) + K256[abs(idx)] + w[abs(idx)] 113 t2 = sigma0(a) + majority(a, b, c) 114 digest_copy[d_position] = (d + t1) & 0xffffffff 115 digest_copy[h_position] = (t1 + t2) & 0xffffffff 116 117 return [(x + digest_copy[idx]) & 0xffffffff for idx, x in enumerate(digest)] 118 119 120def get_buffer(s): 121 if isinstance(s, str): 122 return s 123 if isinstance(s, unicode): 124 try: 125 return str(s) 126 except UnicodeEncodeError: 127 pass 128 return buffer(s) 129 130 131def zeros(count): 132 return [0] * count 133 134 135class SHA256(object): 136 def __init__(self, string=None): 137 self._sha = { 138 'digest': INITIAL_HASH, 139 'count_lo': 0, 140 'count_hi': 0, 141 'data': zeros(BLOCK_SIZE), 142 } 143 if not string: 144 return 145 buff = get_buffer(string) 146 count = len(buff) 147 count_lo = (self._sha['count_lo'] + (count << 3)) & 0xffffffff 148 if count_lo < self._sha['count_lo']: 149 self._sha['count_hi'] += 1 150 self._sha['count_lo'] = count_lo 151 self._sha['count_hi'] += (count >> 29) 152 153 buffer_idx = 0 154 while count >= BLOCK_SIZE: 155 self._sha['data'] = [ord(c) for c in buff[buffer_idx:buffer_idx + BLOCK_SIZE]] 156 count -= BLOCK_SIZE 157 buffer_idx += BLOCK_SIZE 158 self._sha['digest'] = mutate(self._sha['data'], self._sha['digest']) 159 160 self._sha['data'][:count] = [ord(c) for c in buff[buffer_idx:buffer_idx + count]] 161 162 def hexdigest(self): 163 """ 164 A hex digit is an element of the set {0, 1,…, 9, a,…, f}. 165 A hex digit is the representation of a 4-bit string. For example, the hex digit “7” represents 166 the 4-bit string “0111”, and the hex digit “a” represents the 4-bit string “1010”. 167 """ 168 hash = self._sha.copy() 169 count = (hash['count_lo'] >> 3) & 0x3f 170 hash['data'][count] = 0x80 171 count += 1 172 if count > BLOCK_SIZE - 8: 173 # fill with zero bytes after the count 174 hash['data'] = hash['data'][:count] + zeros(BLOCK_SIZE - count) 175 hash['digest'] = mutate(hash['data'], hash['digest']) 176 # fill with zero bytes 177 hash['data'] = [0] * BLOCK_SIZE 178 else: 179 hash['data'] = hash['data'][:count] + zeros(BLOCK_SIZE - count) 180 181 for idx, shift in zip(range(56, 64), range(24, -1, -8) * 2): 182 hash['data'][idx] = (hash['count_hi' if idx < 60 else 'count_lo'] >> shift) & 0xff 183 184 hash['digest'] = mutate(hash['data'], hash['digest']) 185 186 digest = [] 187 for i in hash['digest']: 188 for shift in range(24, -1, -8): 189 digest.append((i >> shift) & 0xff) 190 return ''.join(['%.2x' % i for i in digest[:DIGEST_SIZE]]) 191 192 193def test(): 194 string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' 195 assert 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' == SHA256().hexdigest() 196 assert 'a58dd8680234c1f8cc2ef2b325a43733605a7f16f288e072de8eae81fd8d6433' == SHA256(string).hexdigest() 197 assert 'db7b94909697ac91e9f167159b99a1d2612b5cf4b3086a72cb6ac0206c4bd47c' == SHA256(string * 7).hexdigest() 198 assert '1aa4458852eefd69560827a035db9df11491abdae3483a71d1707f05e085e682' == SHA256('hello⊕').hexdigest() 199 long_text = string * 999 200 assert '5e4e5fcc4c89b7b1b6567d81187e83c99cd7c04ca77a093ed74e35a08046d519' == SHA256(long_text).hexdigest() 201 assert 'c7ae9b6438e9dfccfd486fabed3c08d6f63ae559ef09b2fe084a38dbc46fae7c' == SHA256(u'\uE52D').hexdigest() 202 print('ok') 203 204 205if __name__ == "__main__": 206 test()

error

1--------------------------------------------------------------------------- 2TypeError Traceback (most recent call last) 3<ipython-input-3-495d87c97b96> in <module> 4 219 5 220 if __name__ == "__main__": 6--> 221 test() 7 8<ipython-input-3-495d87c97b96> in test() 9 208 def test(): 10 209 string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.' 11--> 210 assert 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' == SHA256().hexdigest() 12 211 assert 'a58dd8680234c1f8cc2ef2b325a43733605a7f16f288e072de8eae81fd8d6433' == SHA256(string).hexdigest() 13 212 assert 'db7b94909697ac91e9f167159b99a1d2612b5cf4b3086a72cb6ac0206c4bd47c' == SHA256(string * 7).hexdigest() 14 15<ipython-input-3-495d87c97b96> in hexdigest(self) 16 194 hash['data'] = hash['data'][:count] + zeros(BLOCK_SIZE - count) 17 195 18--> 196 for idx, shift in zip(range(56, 64), range(24, -1, -8) * 2): 19 197 hash['data'][idx] = (hash['count_hi' if idx < 60 else 'count_lo'] >> shift) & 0xff 20 198 21 22TypeError: unsupported operand type(s) for *: 'range' and 'int' 23 24In [ ]:

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

range(24, -1, -8) * 2

この部分ですが、 range と int を * で掛け算?しようとするとエラーです。

例えば

list(range(24, -1, -8)) * 2

のようにすると通るようにはなると思います。

下記のように、intをかけることで「繰り返す」という意味になるからです。

>>> [1,2] * 2 [1, 2, 1, 2]

その後はxrangeをrangeにしないといけないなど(Python3だから)また詰まるかと思いますが・・・

そもそも目的はなんなのでしょうか? hashlibなどのライブラリは使ってはいけない?

投稿2019/06/17 09:49

tetsunosuke

総合スコア1292

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2019/06/17 09:58

ありがとうございます。 目的は、SHA256の理解です!
tetsunosuke

2019/06/17 10:02

なるほど。 ちなみに手元の環境で、上記のように修正したところ、 下記の2行は失敗しましたが、その他は通りました。ご参考までに。 assert '1aa4458852eefd69560827a035db9df11491abdae3483a71d1707f05e085e682' == SHA256('hello⊕ ').hexdigest() assert 'c7ae9b6438e9dfccfd486fabed3c08d6f63ae559ef09b2fe084a38dbc46fae7c' == SHA256(u'\uE52D').hexdigest()
退会済みユーザー

退会済みユーザー

2019/06/17 10:10

わたしも同様に確認しました。 Lorem ipsum dolor sit amet, consectetur adipiscing elit. の値は、sha256で確認したところ、同様の結果が得られたので安心しております( ´∀` ) 解答の程、ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.47%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問