コード例 #1
0
 def __del__(self):
     # pylint: disable=protected-access
     if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
         OpenSSL.EVP_CIPHER_CTX_reset(self.ctx)
     else:
         OpenSSL.EVP_CIPHER_CTX_cleanup(self.ctx)
     OpenSSL.EVP_CIPHER_CTX_free(self.ctx)
コード例 #2
0
ファイル: main.py プロジェクト: MS103/studia
def destinguisher(key, iv, msg_list, enc_msg):
    iv2 = increment_iv(iv)
    encryptor = OpenSSL('cbc')
    for i, m in enumerate(msg_list):
        xored = xor_strings(xor_strings(iv, iv2), m)
        enc_m = encryptor.encrypt(xored, key, iv2)
        if enc_m == enc_msg:
            return i, enc_m
コード例 #3
0
def which_msg(enc_type, key, iv, msg_list, enc_msg):
    iv2 = increment_iv(iv)
    encryptor = OpenSSL(enc_type)
    for i, m in enumerate(msg_list):
        xored = xor_strings(xor_strings(iv, iv2), m)
        enc_m = encryptor.encrypt_msg(xored, key, iv2)
        if enc_m == enc_msg:
            return i, enc_m
コード例 #4
0
 def final(self):
     """Returning the final value"""
     i = OpenSSL.c_int(0)
     buffer = OpenSSL.malloc(b"", self.cipher.get_blocksize())
     if (OpenSSL.EVP_CipherFinal_ex(self.ctx, OpenSSL.byref(buffer),
                                    OpenSSL.byref(i))) == 0:
         raise Exception("[OpenSSL] EVP_CipherFinal_ex FAIL ...")
     return buffer.raw[0:i.value]  # pylint: disable=invalid-slice-index
コード例 #5
0
 def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
     """
     do == 1 => Encrypt; do == 0 => Decrypt
     """
     self.cipher = OpenSSL.get_cipher(ciphername)
     self.ctx = OpenSSL.EVP_CIPHER_CTX_new()
     if do == 1 or do == 0:
         k = OpenSSL.malloc(key, len(key))
         IV = OpenSSL.malloc(iv, len(iv))
         OpenSSL.EVP_CipherInit_ex(self.ctx, self.cipher.get_pointer(), 0,
                                   k, IV, do)
     else:
         raise Exception("RTFM ...")
コード例 #6
0
ファイル: invia.py プロジェクト: timendum/sistemats
 def main():
     filename = "fatture.xlsx"
     if len(sys.argv) > 1:
         filename = sys.argv[1]
     if not check_file(filename):
         return
     excel = Excel(filename)
     openssl = OpenSSL("data/SanitelCF.cer")
     configurazione = excel.configurazione()
     try:
         while True:
             try:
                 riga = excel.nuova_riga()
             except ValueError as e:
                 print(e)
                 continue
             if not riga:
                 break
             if riga.get("protocollo"):
                 # riga con già il numero di protocollo
                 continue
             mapped = mapping(configurazione, riga, openssl)
             result = send_data(mapped)
             print("%s - %s" % (mapped["numDocumento"], result[1]))
             excel.protocollo(result[1])
     finally:
         excel.save()
コード例 #7
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def __init__(
        self,
        pubkey=None,
        privkey=None,
        pubkey_x=None,
        pubkey_y=None,
        raw_privkey=None,
        curve='sect283r1',
    ):  # pylint: disable=too-many-arguments
        """
        For a normal and High level use, specifie pubkey,
        privkey (if you need) and the curve
        """
        if isinstance(curve, str):
            self.curve = OpenSSL.get_curve(curve)
        else:
            self.curve = curve

        if pubkey_x is not None and pubkey_y is not None:
            self._set_keys(pubkey_x, pubkey_y, raw_privkey)
        elif pubkey is not None:
            curve, pubkey_x, pubkey_y, _ = ECC._decode_pubkey(pubkey)
            if privkey is not None:
                curve2, raw_privkey, _ = ECC._decode_privkey(privkey)
                if curve != curve2:
                    raise Exception("Bad ECC keys ...")
            self.curve = curve
            self._set_keys(pubkey_x, pubkey_y, raw_privkey)
        else:
            self.privkey, self.pubkey_x, self.pubkey_y = self._generate()
コード例 #8
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def raw_encrypt(
        data,
        pubkey_x,
        pubkey_y,
        curve='sect283r1',
        ephemcurve=None,
        ciphername='aes-256-cbc',
    ):  # pylint: disable=too-many-arguments
        """ECHD encryption, keys supplied in binary data format"""

        if ephemcurve is None:
            ephemcurve = curve
        ephem = ECC(curve=ephemcurve)
        key = sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
        key_e, key_m = key[:32], key[32:]
        pubkey = ephem.get_pubkey()
        iv = OpenSSL.rand(OpenSSL.get_cipher(ciphername).get_blocksize())
        ctx = Cipher(key_e, iv, 1, ciphername)
        ciphertext = iv + pubkey + ctx.ciphering(data)
        mac = hmac_sha256(key_m, ciphertext)
        return ciphertext + mac
コード例 #9
0
ファイル: hash.py プロジェクト: PeterSurda/PyBitmessage
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
コード例 #10
0
 def update(self, input):
     """Update result with more data"""
     i = OpenSSL.c_int(0)
     buffer = OpenSSL.malloc(b"", len(input) + self.cipher.get_blocksize())
     inp = OpenSSL.malloc(input, len(input))
     if OpenSSL.EVP_CipherUpdate(self.ctx, OpenSSL.byref(buffer),
                                 OpenSSL.byref(i), inp, len(input)) == 0:
         raise Exception("[OpenSSL] EVP_CipherUpdate FAIL ...")
     return buffer.raw[0:i.value]  # pylint: disable=invalid-slice-index
コード例 #11
0
ファイル: hash.py プロジェクト: PeterSurda/PyBitmessage
def pbkdf2(password, salt=None, i=10000, keylen=64):
    """Key derivation function using SHA256"""
    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
コード例 #12
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
 def decrypt(self, data, ciphername='aes-256-cbc'):
     """
     Decrypt data with ECIES method using the local private key
     """
     blocksize = OpenSSL.get_cipher(ciphername).get_blocksize()
     iv = data[:blocksize]
     i = blocksize
     _, pubkey_x, pubkey_y, i2 = ECC._decode_pubkey(data[i:])
     i += i2
     ciphertext = data[i:len(data) - 32]
     i += len(ciphertext)
     mac = data[i:]
     key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
     key_e, key_m = key[:32], key[32:]
     if not equals(hmac_sha256(key_m, data[:len(data) - 32]), mac):
         raise RuntimeError("Fail to verify data")
     ctx = Cipher(key_e, iv, 0, ciphername)
     return ctx.ciphering(ciphertext)
コード例 #13
0
def test_mode(file_to_encrypt, mode):
    open_ssl = OpenSSL(mode)
    encrypted_path = file_to_encrypt.replace('.py', '.enc')
    open_ssl.encrypt_file(key, bytes(iv, 'utf-8'), file_to_encrypt,
                          encrypted_path)
    decrypted_path = file_to_encrypt.replace('.py', '.dec')
    open_ssl.decrypt_file(key, bytes(iv, 'utf-8'), encrypted_path,
                          decrypted_path)
    with open(file_to_encrypt, 'rb') as original:
        with open(decrypted_path, 'rb') as decrypted:
            assert original.read() == decrypted.read()

    os.remove(decrypted_path)
    os.remove(encrypted_path)
    print('Test for {} passed'.format(mode))
コード例 #14
0
ファイル: barb.py プロジェクト: robertblackwell/c_http
def action(name, version, defaults):
    print("action: %s %s " % (name, version))
    if name == "boost":
        handler = Boost(name, version, defaults)
    elif name == "openssl":
        handler = OpenSSL(name, version, defaults)
    elif name == "simple_buffer":
        handler = SimpleBuffer(name, version, defaults)
    elif name == "rb_logger":
        handler = RBLogger(name, version, defaults)
    elif name == "http_parser":
        handler = HttpParser(name, version, defaults)
    elif name == "uri-parser":
        handler = UriParser(name, version, defaults)
    elif name == "cxxurl":
        handler = CxxUrl(name, version, defaults)
    elif name == "catch2":
        handler = Catch2(name, version, defaults)
    else:
        return
    handler.get_package()
    handler.stage_package()
    handler.install_package()
コード例 #15
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def _generate(self):
        try:
            pub_key_x = OpenSSL.BN_new()
            pub_key_y = OpenSSL.BN_new()

            key = OpenSSL.EC_KEY_new_by_curve_name(self.curve)
            if key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")
            if (OpenSSL.EC_KEY_generate_key(key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_generate_key FAIL ...")
            if (OpenSSL.EC_KEY_check_key(key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...")
            priv_key = OpenSSL.EC_KEY_get0_private_key(key)

            group = OpenSSL.EC_KEY_get0_group(key)
            pub_key = OpenSSL.EC_KEY_get0_public_key(key)

            if OpenSSL.EC_POINT_get_affine_coordinates_GFp(
                    group, pub_key, pub_key_x, pub_key_y, 0) == 0:
                raise Exception(
                    "[OpenSSL] EC_POINT_get_affine_coordinates_GFp FAIL ...")

            privkey = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(priv_key))
            pubkeyx = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_x))
            pubkeyy = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(pub_key_y))
            OpenSSL.BN_bn2bin(priv_key, privkey)
            privkey = privkey.raw
            OpenSSL.BN_bn2bin(pub_key_x, pubkeyx)
            pubkeyx = pubkeyx.raw
            OpenSSL.BN_bn2bin(pub_key_y, pubkeyy)
            pubkeyy = pubkeyy.raw
            self.raw_check_key(privkey, pubkeyx, pubkeyy)

            return privkey, pubkeyx, pubkeyy

        finally:
            OpenSSL.EC_KEY_free(key)
            OpenSSL.BN_free(pub_key_x)
            OpenSSL.BN_free(pub_key_y)
コード例 #16
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None):
        """Check key validity, key is supplied as binary data"""
        if curve is None:
            curve = self.curve
        elif isinstance(curve, str):
            curve = OpenSSL.get_curve(curve)
        else:
            curve = curve
        try:
            key = OpenSSL.EC_KEY_new_by_curve_name(curve)
            if key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")
            if privkey is not None:
                priv_key = OpenSSL.BN_bin2bn(privkey, len(privkey), 0)
            pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0)
            pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0)

            if privkey is not None:
                if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0:
                    raise Exception(
                        "[OpenSSL] EC_KEY_set_private_key FAIL ...")

            group = OpenSSL.EC_KEY_get0_group(key)
            pub_key = OpenSSL.EC_POINT_new(group)

            if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(
                    group, pub_key, pub_key_x, pub_key_y, 0)) == 0:
                raise Exception(
                    "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...")
            if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...")
            if (OpenSSL.EC_KEY_check_key(key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...")
            return 0

        finally:
            OpenSSL.EC_KEY_free(key)
            OpenSSL.BN_free(pub_key_x)
            OpenSSL.BN_free(pub_key_y)
            OpenSSL.EC_POINT_free(pub_key)
            if privkey is not None:
                OpenSSL.BN_free(priv_key)
コード例 #17
0
                          decrypted_path)
    with open(file_to_encrypt, 'rb') as original:
        with open(decrypted_path, 'rb') as decrypted:
            assert original.read() == decrypted.read()

    os.remove(decrypted_path)
    os.remove(encrypted_path)
    print('Test for {} passed'.format(mode))


if __name__ == '__main__':
    command_line_parser = CommandLineParser()
    parsed_args = command_line_parser.parse_arguments(sys.argv[1:])

    enc_type = 'cbc'
    openssl = OpenSSL(enc_type)
    iv = '0' * 16
    iv2 = increment_iv(iv)
    ks = jks.KeyStore.load(parsed_args['keystore_path'],
                           parsed_args['password'])
    key = ks.private_keys['self signed cert'].pkey[:32]

    msg_list = ['lubie placki bar', 'pala lufa jedyna']
    msg_list = [x[:16] for x in msg_list]
    rand = randint(0, 1)
    random_msg = msg_list[rand]

    enc_m1 = openssl.encrypt_msg(random_msg, key, iv)
    print('Encrypting "{}" to {}'.format(random_msg, enc_m1))

    ind, cipher = which_msg(enc_type, key, iv, msg_list, enc_m1)
コード例 #18
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def sign(self, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
        """
        Sign the input with ECDSA method and returns the signature
        """
        try:
            size = len(inputb)
            buff = OpenSSL.malloc(inputb, size)
            digest = OpenSSL.malloc(0, 64)
            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                md_ctx = OpenSSL.EVP_MD_CTX_new()
            else:
                md_ctx = OpenSSL.EVP_MD_CTX_create()
            dgst_len = OpenSSL.pointer(OpenSSL.c_int(0))
            siglen = OpenSSL.pointer(OpenSSL.c_int(0))
            sig = OpenSSL.malloc(0, 151)

            key = OpenSSL.EC_KEY_new_by_curve_name(self.curve)
            if key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")

            priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey), 0)
            pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0)
            pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0)

            if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...")

            group = OpenSSL.EC_KEY_get0_group(key)
            pub_key = OpenSSL.EC_POINT_new(group)

            if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(
                    group, pub_key, pub_key_x, pub_key_y, 0)) == 0:
                raise Exception(
                    "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...")
            if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...")
            if (OpenSSL.EC_KEY_check_key(key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...")

            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                OpenSSL.EVP_MD_CTX_new(md_ctx)
            else:
                OpenSSL.EVP_MD_CTX_init(md_ctx)
            OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None)

            if (OpenSSL.EVP_DigestUpdate(md_ctx, buff, size)) == 0:
                raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...")
            OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len)
            OpenSSL.ECDSA_sign(0, digest, dgst_len.contents, sig, siglen, key)
            if (OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, sig,
                                     siglen.contents, key)) != 1:
                raise Exception("[OpenSSL] ECDSA_verify FAIL ...")

            return sig.raw[:siglen.contents.value]

        finally:
            OpenSSL.EC_KEY_free(key)
            OpenSSL.BN_free(pub_key_x)
            OpenSSL.BN_free(pub_key_y)
            OpenSSL.BN_free(priv_key)
            OpenSSL.EC_POINT_free(pub_key)
            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                OpenSSL.EVP_MD_CTX_free(md_ctx)
            else:
                OpenSSL.EVP_MD_CTX_destroy(md_ctx)
コード例 #19
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def verify(self, sig, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
        """
        Verify the signature with the input and the local public key.
        Returns a boolean
        """
        try:
            bsig = OpenSSL.malloc(sig, len(sig))
            binputb = OpenSSL.malloc(inputb, len(inputb))
            digest = OpenSSL.malloc(0, 64)
            dgst_len = OpenSSL.pointer(OpenSSL.c_int(0))
            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                md_ctx = OpenSSL.EVP_MD_CTX_new()
            else:
                md_ctx = OpenSSL.EVP_MD_CTX_create()
            key = OpenSSL.EC_KEY_new_by_curve_name(self.curve)

            if key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")

            pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0)
            pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0)
            group = OpenSSL.EC_KEY_get0_group(key)
            pub_key = OpenSSL.EC_POINT_new(group)

            if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(
                    group, pub_key, pub_key_x, pub_key_y, 0)) == 0:
                raise Exception(
                    "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...")
            if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...")
            if (OpenSSL.EC_KEY_check_key(key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...")
            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                OpenSSL.EVP_MD_CTX_new(md_ctx)
            else:
                OpenSSL.EVP_MD_CTX_init(md_ctx)
            OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None)
            if (OpenSSL.EVP_DigestUpdate(md_ctx, binputb, len(inputb))) == 0:
                raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...")

            OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len)
            ret = OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, bsig,
                                       len(sig), key)

            if ret == -1:
                # Fail to Check
                return False
            if ret == 0:
                # Bad signature !
                return False
            # Good
            return True

        finally:
            OpenSSL.EC_KEY_free(key)
            OpenSSL.BN_free(pub_key_x)
            OpenSSL.BN_free(pub_key_y)
            OpenSSL.EC_POINT_free(pub_key)
            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                OpenSSL.EVP_MD_CTX_free(md_ctx)
            else:
                OpenSSL.EVP_MD_CTX_destroy(md_ctx)
コード例 #20
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
 def get_curve(self):
     """Encryption object from curve name"""
     return OpenSSL.get_curve_by_id(self.curve)
コード例 #21
0
ファイル: main.py プロジェクト: davidshen84/docker-autocert
 def get(self):
     openssl = OpenSSL()
     version = openssl.version()
     self.write(version)
コード例 #22
0
s = 16  # len(secret)
n = 24  # len(msg)
# N = pow(2, n)  # len(secrets)
N = 1000

# Placeholder
msgs = []
keys = []
secrets = []
start = time.time()
# ALICE (Encryption)
for i in range(0, N):
    secret = str(randint(1000000000000000000000000, 9999999999999999999999999))
    key = str(randint(1000, 9999))

    enc_suite = OpenSSL('cbc')
    msg = enc_suite.encrypt('0' * (n - s) + secret, key * 4, key * 4)

    msgs.append(msg)
    keys.append(key)
    secrets.append(secret)

# ALICE sends "msgs" Block to BOB

# BOB (Brute force Decryption)
decrypted_msg = ''
rand_msg_solve = randint(0, N - 1)

print("Start decrypting at {}".format(time.time() - start))
keys = [str(x) for x in range(1000, 9999)]
while not decrypted_msg[:(n - s)] == '0' * (n - s):
コード例 #23
0
ファイル: tests.py プロジェクト: MS103/studia
from openssl import OpenSSL

command_line_parser = CommandLineParser()
parsed_args = command_line_parser.parse_arguments(sys.argv[1:])

key_store = jks.KeyStore.load(parsed_args['keystore_path'],
                              parsed_args['password'])
key = key_store.private_keys['alias_name'].pkey[:32]

num_of_success = 0
msg_to_enc = 'x'
types_of_enc = ['ofb', 'cbc', 'ctr']
if True:
    for enc_type in types_of_enc:
        print('Sprawdzam szyfrowanie i deszyfrowanie dla ', enc_type.upper())
        openssl = OpenSSL(enc_type)
        iv = '0' * 16
        enc_m = openssl.encrypt(msg_to_enc, key, iv)
        dec_m = openssl.decrypt(enc_m, key, iv).rstrip(b'\x00')
        try:
            dec_m = dec_m.decode()
            if_success = msg_to_enc == dec_m
        except UnicodeDecodeError as e:
            print("Wystąpił błąd!", e)
            if_success = 0
        num_of_success += if_success
        print('Sprawdzam czy {a} == {b}. Rezultat to {c}\n'.format(
            a=msg_to_enc, b=dec_m, c=if_success))
    print('Stosunek sukcesów do prób to {a}/{b}'.format(a=num_of_success,
                                                        b=len(types_of_enc)))
コード例 #24
0
def randomBytes(n):
    """Method randomBytes."""
    try:
        return os.urandom(n)
    except NotImplementedError:
        return OpenSSL.rand(n)
コード例 #25
0
ファイル: main.py プロジェクト: MS103/studia
def destinguisher(key, iv, msg_list, enc_msg):
    iv2 = increment_iv(iv)
    encryptor = OpenSSL('cbc')
    for i, m in enumerate(msg_list):
        xored = xor_strings(xor_strings(iv, iv2), m)
        enc_m = encryptor.encrypt(xored, key, iv2)
        if enc_m == enc_msg:
            return i, enc_m


command_line_parser = CommandLineParser()
parsed_args = command_line_parser.parse_arguments(sys.argv[1:])

enc_type = 'cbc'
openssl = OpenSSL(enc_type)
iv = '0' * 16
key_store = jks.KeyStore.load(parsed_args['keystore_path'],
                              parsed_args['password'])
key = key_store.private_keys['alias_name'].pkey[:32]

f = open(parsed_args['input_path'], 'r')
input_ms = [x for x in f]
f = open(r'C:\Users\Latitude\Desktop\output.txt', 'w')

if len(input_ms) == 0:
    raise IOError('Za mało danych wejściowych')
elif len(input_ms) == 2:
    msg_list = [x[:16] for x in input_ms]
    random_msg = msg_list[randint(0, 1)]
コード例 #26
0
 def get_blocksize(ciphername):
     """This Method returns cipher blocksize"""
     cipher = OpenSSL.get_cipher(ciphername)
     return cipher.get_blocksize()
コード例 #27
0
ファイル: ecc.py プロジェクト: PeterSurda/PyBitmessage
    def raw_get_ecdh_key(self, pubkey_x, pubkey_y):
        """ECDH key as binary data"""
        try:
            ecdh_keybuffer = OpenSSL.malloc(0, 32)

            other_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve)
            if other_key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")

            other_pub_key_x = OpenSSL.BN_bin2bn(pubkey_x, len(pubkey_x), 0)
            other_pub_key_y = OpenSSL.BN_bin2bn(pubkey_y, len(pubkey_y), 0)

            other_group = OpenSSL.EC_KEY_get0_group(other_key)
            other_pub_key = OpenSSL.EC_POINT_new(other_group)

            if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(
                    other_group, other_pub_key, other_pub_key_x,
                    other_pub_key_y, 0)) == 0:
                raise Exception(
                    "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...")
            if (OpenSSL.EC_KEY_set_public_key(other_key, other_pub_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...")
            if (OpenSSL.EC_KEY_check_key(other_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...")

            own_key = OpenSSL.EC_KEY_new_by_curve_name(self.curve)
            if own_key == 0:
                raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...")
            own_priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey),
                                             0)

            if (OpenSSL.EC_KEY_set_private_key(own_key, own_priv_key)) == 0:
                raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...")

            if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL:
                OpenSSL.EC_KEY_set_method(own_key, OpenSSL.EC_KEY_OpenSSL())
            else:
                OpenSSL.ECDH_set_method(own_key, OpenSSL.ECDH_OpenSSL())
            ecdh_keylen = OpenSSL.ECDH_compute_key(ecdh_keybuffer, 32,
                                                   other_pub_key, own_key, 0)

            if ecdh_keylen != 32:
                raise Exception("[OpenSSL] ECDH keylen FAIL ...")

            return ecdh_keybuffer.raw

        finally:
            OpenSSL.EC_KEY_free(other_key)
            OpenSSL.BN_free(other_pub_key_x)
            OpenSSL.BN_free(other_pub_key_y)
            OpenSSL.EC_POINT_free(other_pub_key)
            OpenSSL.EC_KEY_free(own_key)
            OpenSSL.BN_free(own_priv_key)
コード例 #28
0
 def gen_IV(ciphername):
     """Generate random initialization vector"""
     cipher = OpenSSL.get_cipher(ciphername)
     return OpenSSL.rand(cipher.get_blocksize())