Mask generation function: Difference between revisions

Content deleted Content added
m Capitalising short description "cryptographic tool" per WP:SDFORMAT (via Bandersnatch)
Line 65:
import hashlib
 
def i2ospmgf1(integerseed: intbytes, sizelength: int, hash_func= 4hashlib.sha1) -> strbytes:
hLen = hash_func().digest_size
return b"".join([chr((integer >> (8 * i)) & 0xFF).encode() for i in reversed(range(size))])
# https://www.ietf.org/rfc/rfc2437.txt
 
# 1.If l > 2^32(hLen), output "mask too long" and stop.
def mgf1(input_str: bytes, length: int, hash_func=hashlib.sha1) -> str:
if length > (hLen << 32):
"""Mask generation function."""
raise ValueError("mask too long")
# 2.Let T be the empty octet string.
T = b""
# 3.For counter from 0 to \lceil{l / hLen}\rceil-1, do the following:
# Note: \lceil{l / hLen}\rceil-1 is the number of iterations needed,
# but it's easier to check if we have reached the desired length.
counter = 0
outputwhile =len(T) b""< length:
# a.Convert counter to an octet string C of length 4 with the primitive I2OSP: C = I2OSP (counter, 4)
while len(output) < length:
C = i2ospint.to_bytes(counter, 4, 'big')
# b.Concatenate the hash of the seed Z and C to the octet string T: T = T || Hash (Z || C)
outputT += hash_func(input_strseed + C).digest()
counter += 1
# 4.Output the leading l octets of T as the octet string mask.
return outputT[:length]
</syntaxhighlight>
 
Line 82 ⟶ 90:
 
<syntaxhighlight lang="pycon">
Python 3.10.04 (tags/v3.10.0:b494f59main, OctApr 16 4 20212022, 1916:0028:1841) [MSCGCC v8.1929 64 bit (AMD64)3.0] on win32linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> from mgf1 import mgf1
>>> from binascii import hexlify
>>> from hashlib import sha256
>>> hexlify(mgf1('b"foo'", 3).hex()
'1ac907'
>>> hexlify(mgf1('b"foo'", 5).hex()
'1ac9075cd4'
>>> hexlify(mgf1('b"bar'", 5).hex()
'bc0c655e01'
>>> hexlify(mgf1('b"bar'", 50).hex()
'bc0c655e016bc2931d85a2e675181adcef7f581f76df2739da74faac41627be2f7f415c89e983fd0ce80ced9878641cb4876'
>>> hexlify(mgf1('b"bar'", 50, sha256).hex()
'382576a7841021cc28fc4c0948753fb8312090cea942ea4c4e735d10dc724b155f9f6069f289d61daca0cb814502ef04eae1'
</syntaxhighlight>