示例#1
0
 def test_nonexistent_cipher(self, mode):
     b = Backend()
     b.register_cipher_adapter(
         DummyCipherAlgorithm, type(mode),
         lambda backend, cipher, mode: backend._ffi.NULL)
     cipher = Cipher(
         DummyCipherAlgorithm(),
         mode,
         backend=b,
     )
     with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
         cipher.encryptor()
示例#2
0
 def test_nonexistent_cipher(self, mode):
     b = Backend()
     b.register_cipher_adapter(
         DummyCipher,
         type(mode),
         lambda backend, cipher, mode: backend._ffi.NULL
     )
     cipher = Cipher(
         DummyCipher(), mode, backend=b,
     )
     with pytest.raises(UnsupportedCipher):
         cipher.encryptor()
示例#3
0
 def test_nonexistent_cipher(self, mode):
     b = Backend()
     b.register_cipher_adapter(
         DummyCipherAlgorithm,
         type(mode),
         lambda backend, cipher, mode: backend._ffi.NULL
     )
     cipher = Cipher(
         DummyCipherAlgorithm(), mode, backend=b,
     )
     with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER):
         cipher.encryptor()
示例#4
0
 def test_nonexistent_cipher(self, mode):
     b = Backend()
     b.register_cipher_adapter(
         DummyCipher,
         type(mode),
         lambda backend, cipher, mode: backend._ffi.NULL
     )
     cipher = Cipher(
         DummyCipher(), mode, backend=b,
     )
     with pytest.raises(UnsupportedAlgorithm):
         cipher.encryptor()
示例#5
0
def _convert_rsa_private_key(keypair):
    backend = Backend()

    def _trim_bn_to_int(s):
        binary = s.lstrip(b'\x00')
        bn_ptr = backend._lib.BN_bin2bn(binary, len(binary), backend._ffi.NULL)
        try:
            return backend._bn_to_int(bn_ptr)
        finally:
            backend._lib.OPENSSL_free(bn_ptr)

    (n, e, d, iqmp, p, q) = [
        _trim_bn_to_int(value)
        for value in _read_KEY_RSA(io.BytesIO(keypair.private_key))
    ]

    numbers = RSAPrivateNumbers(
        d=d,
        p=p,
        q=q,
        dmp1=rsa_crt_dmp1(d, p),
        dmq1=rsa_crt_dmq1(d, q),
        iqmp=rsa_crt_iqmp(p, q),
        public_numbers=RSAPublicNumbers(e=e, n=n),
    )

    return numbers.private_key(backend)
示例#6
0
def desencriptar(aes_key, input_):
    output_ = None
    init_vector, tag, seleccion_encriptada = split(input_)

    cipher = Cipher(algorithms.AES(aes_key), modes.GCM(init_vector, tag),
                    backend=Backend())
    decryptor = cipher.decryptor()
    output_ = decryptor.update(seleccion_encriptada) + decryptor.finalize()
    return output_
示例#7
0
def encriptar(aes_key, input_, init_vector=None):
    if init_vector is None:
        init_vector = generate_random_bytes()
    cipher = Cipher(algorithms.AES(aes_key), modes.GCM(init_vector),
                    backend=Backend())
    encryptor = cipher.encryptor()
    encrypted = encryptor.update(input_) + encryptor.finalize()
    encrypted = init_vector + encryptor.tag + encrypted
    return encrypted
示例#8
0
文件: secrets.py 项目: thegcat/pretix
 def _sign_payload(self, payload):
     if not self.event.settings.ticket_secrets_pretix_sig1_privkey:
         self._generate_keys()
     privkey = load_pem_private_key(
         base64.b64decode(
             self.event.settings.ticket_secrets_pretix_sig1_privkey), None,
         Backend())
     signature = privkey.sign(payload)
     return (bytes([0x01]) + struct.pack(">H", len(payload)) +
             struct.pack(">H", len(signature)) + payload + signature)
示例#9
0
def derivar_clave(pin, salt):
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=16,
        salt=salt,
        iterations=1000000,
        backend=Backend()
    )
    clave = kdf.derive(pin)
    return clave
示例#10
0
    def setup_class(cls):
        cls.custom_signed_data = json.dumps(cls.test_receipt).encode('ascii')
        cls.custom_priv_key = rsa.generate_private_key(public_exponent=65537,
                                                       key_size=1024,
                                                       backend=Backend())
        cls.custom_pub_key_bytes = b64encode(
            cls.custom_priv_key.public_key().public_bytes(
                Encoding.DER, PublicFormat.SubjectPublicKeyInfo))

        signer = cls.custom_priv_key.signer(PKCS1v15(), hashes.SHA1())
        signer.update(cls.custom_signed_data)
        cls.custom_signature = b64encode(signer.finalize())

        cls.input_data['receipt'] = {
            'payload': cls.custom_signed_data,
            'signature': cls.custom_signature,
        }
示例#11
0
文件: secrets.py 项目: thegcat/pretix
    def _parse(self, secret):
        try:
            rawbytes = base64.b64decode(secret[::-1])
            if rawbytes[0] != 1:
                raise ValueError('Invalid version')

            payload_len = struct.unpack(">H", rawbytes[1:3])[0]
            sig_len = struct.unpack(">H", rawbytes[3:5])[0]
            payload = rawbytes[5:5 + payload_len]
            signature = rawbytes[5 + payload_len:5 + payload_len + sig_len]
            pubkey = load_pem_public_key(
                base64.b64decode(
                    self.event.settings.ticket_secrets_pretix_sig1_pubkey),
                Backend())
            pubkey.verify(signature, payload)
            t = pretix_sig1_pb2.Ticket()
            t.ParseFromString(payload)
            return t
        except:
            return None
示例#12
0
    def _disect_receipt(self, payload, encoded=True):
        """
        Signature format

        (big endian)
        +-----------------+-----------+------------------+-------------+
        | receipt version | signature | certificate size | certificate |
        +=================+===========+==================+=============+
        |          1 byte | 128 bytes |          4 bytes |       ->EOF |
        +-----------------+-----------+------------------+-------------+
        """
        pkcs7_der = b64decode(payload).decode('ascii') if encoded else payload
        signature_pattern = r'(?:"signature" = ")([^\"]+)";'
        info_pattern = '(?:"purchase-info" = ")([^\"]+)";'

        re_signature = re.search(signature_pattern, pkcs7_der, re.M)
        raw_signature = b64decode(re_signature.group(1))

        # TODO - get the first byte only
        receipt_version = unpack('>b', bytes(raw_signature[0:1]))[0]
        signature = unpack('128s', raw_signature[1:129])[0]
        cert_size = unpack('>I', raw_signature[129:133])[0]
        certificate_der = unpack('%ss' % cert_size, raw_signature[133:])[0]

        assert len(certificate_der) == cert_size
        assert len(signature) == 128
        assert receipt_version == 2

        # PKCS7 cert from PKCS7 DER blob
        # TODO - add more certificate checks (ie. issuer == 'Apple Inc.')
        certificate = load_der_x509_certificate(certificate_der, Backend())

        re_info = re.search(info_pattern, pkcs7_der, re.MULTILINE)
        raw_purchase_info = b64decode(re_info.group(1))
        # signed data is concatenated & packed `receipt version` + `purchase info`
        signed_data = pack("b%ss" % len(raw_purchase_info), receipt_version,
                           raw_purchase_info)
        return certificate, signature, signed_data
示例#13
0
import base64
import secrets
import binascii
import hashlib
import hmac
import struct
import pysodium
from cryptography.hazmat.primitives.kdf import hkdf
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends.openssl.backend import Backend
import re

openssl_backend = Backend()

MAGIC_HEADER = b'nacl:'
NONCE_SIZE = 24
DS_BIDX = b"\x7E" * 32
DS_FENC = b"\xB4" * 32
CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE = 4
CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE = 33554432


class Transformation:
    @classmethod
    def last_four_digits(cls, item: str):
        item = re.sub(r'/[^0-9]/', '', item)
        item = item.rjust(4, '0')
        item = item[-4:]
        return item.encode()

    @classmethod
示例#14
0
 def _set_key(self, public_key):
     # Key from Google Play is a X.509 subjectPublicKeyInfo DER SEQUENCE.
     self.public_key = load_der_public_key(base64.b64decode(public_key),
                                           Backend())