2019-09-20 10:10:25 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
import hashlib
|
|
|
|
|
|
|
|
from cryptography.exceptions import InvalidSignature
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
|
|
|
2019-09-20 15:41:56 +02:00
|
|
|
def verify_signature(public_key_path, input_data, signature_data):
|
2019-09-20 10:10:25 +02:00
|
|
|
# Verifies ECDSA HMAC SHA512 signature of a file
|
2019-09-20 15:41:56 +02:00
|
|
|
with open(public_key_path, 'rb') as f:
|
2019-09-20 10:10:25 +02:00
|
|
|
pub_key = serialization.load_pem_public_key(f.read(), default_backend())
|
2019-09-20 15:41:56 +02:00
|
|
|
pub_key.verify(signature_data, input_data, ec.ECDSA(hashes.SHA512()))
|
2019-09-20 10:10:25 +02:00
|
|
|
|
2019-09-20 15:41:56 +02:00
|
|
|
def verify_hash(input_path, expected_hash):
|
2019-09-20 10:10:25 +02:00
|
|
|
# Verifies SHA512 hash of a file against expected hash
|
|
|
|
sha512 = hashlib.sha512()
|
2019-09-20 15:41:56 +02:00
|
|
|
with open(input_path, 'rb') as f:
|
2019-09-20 10:10:25 +02:00
|
|
|
while True:
|
|
|
|
data = f.read(65536)
|
|
|
|
if not data:
|
|
|
|
break
|
|
|
|
sha512.update(data)
|
|
|
|
if sha512.hexdigest() != expected_hash:
|
2019-09-20 15:41:56 +02:00
|
|
|
raise InvalidSignature(input_path)
|