summaryrefslogtreecommitdiff
path: root/postgresqleu/util/crypto.py
blob: 62829bf26a943cc2c146d3867457df83f69214ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from django.core.exceptions import ValidationError

from Cryptodome.PublicKey import RSA
from Cryptodome.Hash import SHA256, SHA1
from Cryptodome.Signature import pkcs1_15
from Cryptodome.Util.number import long_to_bytes

import base64


def validate_pem_public_key(value):
    try:
        k = RSA.importKey(value)
        if k.has_private():
            raise ValidationError("This should be a public key, but contains a private key")
    except ValidationError:
        raise
    except Exception as e:
        raise ValidationError("Could not validate public key: {}".format(e))


def validate_pem_private_key(value):
    try:
        k = RSA.importKey(value)
        if not k.has_private():
            raise ValidationError("This should be a private key, but doesn't contain one")
    except ValidationError:
        raise
    except Exception as e:
        raise ValidationError("Could not validate private key: {}".format(e))


def generate_rsa_keypair(bits=2048):
    key = RSA.generate(bits)
    return (
        key.export_key().decode('utf8'),
        key.publickey().export_key().decode('utf8'),
    )


def rsa_sign_string_sha256(privatekeystr, msg):
    key = RSA.importKey(privatekeystr)
    h = SHA256.new(msg.encode('ascii'))
    sig = pkcs1_15.new(key).sign(h)
    return sig


def rsa_verify_string_sha1(publickeystr, msg, sig):
    key = RSA.importKey(publickeystr)
    h = SHA1.new(msg)
    try:
        pkcs1_15.new(key).verify(h, sig)
        return True
    except ValueError:
        # Raises ValueError if the signature is wrong
        return False


def rsa_get_jwk_struct(publickeystr, kid):
    key = RSA.importKey(publickeystr)
    return {
        'use': 'sig',
        'alg': 'RS256',
        'kty': 'RSA',
        'kid': kid,
        'n': base64.urlsafe_b64encode(long_to_bytes(key.publickey().n)).strip(b'=').decode(),
        'e': base64.urlsafe_b64encode(long_to_bytes(key.publickey().e)).strip(b'=').decode(),
    }