vmmgr/usr/lib/python3.6/lxcmgr/crypto.py

27 lines
983 B
Python
Raw Normal View History

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
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
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())
pub_key.verify(signature_data, input_data, ec.ECDSA(hashes.SHA512()))
2019-09-20 10:10:25 +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()
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:
raise InvalidSignature(input_path)