PyBitmessage-2021-04-27/src/pyelliptic/hash.py

71 lines
1.8 KiB
Python
Raw Normal View History

2019-09-23 14:22:56 +02:00
"""
Wrappers for hash functions from OpenSSL.
2019-09-23 14:22:56 +02:00
"""
2013-01-16 17:52:52 +01:00
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
# See LICENSE for details.
from .openssl import OpenSSL
2013-01-16 17:52:52 +01:00
2014-12-25 09:57:34 +01:00
# For python3
def _equals_bytes(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= x ^ y
return result == 0
def _equals_str(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
def equals(a, b):
2019-09-23 14:21:58 +02:00
"""Compare two strings or bytearrays"""
2014-12-25 09:57:34 +01:00
if isinstance(a, str):
return _equals_str(a, b)
2019-09-23 14:22:56 +02:00
return _equals_bytes(a, b)
2014-12-25 09:57:34 +01:00
2013-01-16 17:52:52 +01:00
def hmac_sha256(k, m):
"""
Compute the key and the message with HMAC SHA5256
"""
key = OpenSSL.malloc(k, len(k))
d = OpenSSL.malloc(m, len(m))
md = OpenSSL.malloc(0, 32)
i = OpenSSL.pointer(OpenSSL.c_int(0))
OpenSSL.HMAC(OpenSSL.EVP_sha256(), key, len(k), d, len(m), md, i)
return md.raw
def hmac_sha512(k, m):
"""
Compute the key and the message with HMAC SHA512
"""
key = OpenSSL.malloc(k, len(k))
d = OpenSSL.malloc(m, len(m))
md = OpenSSL.malloc(0, 64)
i = OpenSSL.pointer(OpenSSL.c_int(0))
OpenSSL.HMAC(OpenSSL.EVP_sha512(), key, len(k), d, len(m), md, i)
return md.raw
def pbkdf2(password, salt=None, i=10000, keylen=64):
2019-09-23 14:22:56 +02:00
"""Key derivation function using SHA256"""
2013-01-16 17:52:52 +01:00
if salt is None:
salt = OpenSSL.rand(8)
p_password = OpenSSL.malloc(password, len(password))
p_salt = OpenSSL.malloc(salt, len(salt))
output = OpenSSL.malloc(0, keylen)
OpenSSL.PKCS5_PBKDF2_HMAC(p_password, len(password), p_salt,
len(p_salt), i, OpenSSL.EVP_sha256(),
keylen, output)
return salt, output.raw