예제 #1
0
    def load_key(self, filename):
        """
        Load signing key (from pem file)
        """
        default_sk = SigningKey.from_pem(keys_default_pem)

        with open(filename, "r") as sk_file:
            sk_pem = sk_file.read()

        self.sk = SigningKey.from_pem(sk_pem)

        sk_hex = "".join(c.encode('hex') for c in self.sk.to_string())
        return default_sk.to_string() == self.sk.to_string()
예제 #2
0
    def doAuthenticate(self, msg):
        if len(msg.args) == 1 and msg.args[0] == '+':
            log.info('%s: Authenticating using SASL.', self.network)

            if self.sasl == 'external':
                authstring = '+'
            elif self.sasl == 'ecdsa-nist256p-challenge':
                authstring = base64.b64encode(
                    self.sasl_username.encode('utf-8')).decode('utf-8')
            elif self.sasl == 'plain':
                authstring = base64.b64encode('\0'.join([
                    self.sasl_username,
                    self.sasl_username,
                    self.sasl_password
                ]).encode('utf-8')).decode('utf-8')

            self.queueMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,)))
        elif (len(msg.args) == 1 and msg.args[0] != '+' and
                self.sasl == 'ecdsa-nist256p-challenge'):
            try:
                private_key = SigningKey.from_pem(open(self.sasl_ecdsa_key).
                    read())
                authstring = base64.b64encode(
                    private_key.sign(base64.b64decode(msg.args[0].encode()))).decode('utf-8')
            except (BadDigestError, OSError, ValueError) as e:
                authstring = "*"

            self.queueMsg(ircmsgs.IrcMsg(command='AUTHENTICATE', args=(authstring,)))
예제 #3
0
def sign_subscription(signatory, subscription, private_key_string, public_key_string):
    """
    sign a subscription (deep hash of criteria, signatory, signature timestamp, public key)
    param signatory: Name or identifier of the signing party (the caller)
    param subscription: all fields of subscription signed
    param private_key_string: private key used for generating signature
    param public_key_string: hashed and inserted into signature block for later validation
    """
    ecdsa_signing_key = SigningKey.from_pem(private_key_string)
    signature_ts = int(time.time())
    hashed_items = []

    # append criteria for hashing
    hashed_items.append(deep_hash(subscription['criteria']))

    # append sub create timestamp for hashing
    hashed_items.append(subscription['create_ts'])

    hashed_items.append(signatory)
    hashed_items.append(signature_ts)
    hashed_items.append(public_key_string)

    verification_hash = final_hash(hashed_items)

    signature = ecdsa_signing_key.sign(verification_hash)
    digest = signature.encode('base64')

    signature_block = assemble_sig_block(subscription, signatory, public_key_string, digest, verification_hash, signature_ts)

    return signature_block
예제 #4
0
    def load_private_key(self):
        if self.private_key is None:
            msg = 'Please, specify the private_key location.'
            raise ValueError(msg)

        with open(self.private_key, 'rb') as key_file:
            return SigningKey.from_pem(key_file.read())
예제 #5
0
def load(privkeypem):
    """
    Load a private key from disk
    :param privkeypem:
    :return:
    """
    with open(privkeypem, "rb") as privfile:
        return SigningKey.from_pem(privfile.read())
예제 #6
0
 def test_sign(self):
   pem = '-----BEGIN EC PRIVATE KEY-----\nMHQCAQEEICg7E4NN53YkaWuAwpoqjfAofjzKI7Jq1f532dX+0O6QoAcGBSuBBAAK\noUQDQgAEjZcNa6Kdz6GQwXcUD9iJ+t1tJZCx7hpqBuJV2/IrQBfue8jh8H7Q/4vX\nfAArmNMaGotTpjdnymWlMfszzXJhlw==\n-----END EC PRIVATE KEY-----\n'
   signed = utils.sign("message", pem)
   sk = SigningKey.from_pem(pem)
   vk = sk.get_verifying_key()
   print(signed)
   signed = binascii.unhexlify(signed)
   vk.verify(signed, "message".encode(), hashfunc=hashlib.sha256, sigdecode=ecdsaUtil.sigdecode_der)
예제 #7
0
 def __sign_message(cls, key_path, message):
     key_data = open(key_path).read()
     signing_key = SigningKey.from_pem(key_data)
     signature = signing_key.sign(
         message,
         hashfunc=hashlib.sha256,
         sigencode=ecdsa.util.sigencode_der
     )
     signature = base64.b64encode(signature)
     return signature
예제 #8
0
    def __init__(self, **kwargs):
        try:
            config = kwargs['config']
        except KeyError:
            client_key = kwargs['client_key']
            server_key = kwargs['server_key']
            identifier = kwargs['identifier']
            try:
                url = kwargs['url']
            except KeyError:
                url = 'https://core.bravecollective.net/api'
        else:
            client_key = config['CORE_AUTH_PRIVATE_KEY']
            server_key = config['CORE_AUTH_PUBLIC_KEY']
            identifier = config['CORE_AUTH_IDENTIFIER']
            try:
                url = config['CORE_AUTH_URL']
            except KeyError:
                url = 'https://core.bravecollective.net/api'

        if isinstance(client_key, SigningKey):
            priv = client_key
        elif hasattr(client_key, 'read'):
            priv_pem = client_key.read()
            priv = SigningKey.from_pem(priv_pem)
        else:
            with open(client_key, 'r') as f:
                priv_pem = f.read()
                priv = SigningKey.from_pem(priv_pem)

        if isinstance(server_key, VerifyingKey):
            pub = server_key
        elif hasattr(server_key, 'read'):
            pub_pem = server_key.read()
            pub = VerifyingKey.from_pem(pub_pem)
        else:
            with open(server_key, 'r') as f:
                pub_pem = f.read()
                pub = VerifyingKey.from_pem(pub_pem)

        self.api = API(url, identifier, priv, pub,
                requests_session)
def get_signKey(self, usrID):    
        """ 
        Get the user's sign key
        Returns:
            The sign key
        """

        filename = '/opt/stack/swift/swift/common/middleware/sk.key'
        with open(filename, 'r') as f:
            sign_key = f.read()
        return SigningKey.from_pem(sign_key)
예제 #10
0
파일: encryptator.py 프로젝트: magarcia/C
def sign_file(args):
    from ecdsa import SigningKey

    private_key = SigningKey.from_pem(args.signatureKey.read())
    message = args.file.read()

    name = os.path.basename(args.file.name)

    signature = sign(private_key, message)
    with open('%s.sig' % name, 'wb') as sign_file:
        sign_file.write(signature)
def make_ecc_secure_signature(alg_dir_path, common_head_content, section_content):
    first_key_dir = os.path.join(alg_dir_path, r'upg_private_ecc_1.pem')
    second_key_dir = os.path.join(alg_dir_path, r'upg_private_ecc_2.pem')
    with open(first_key_dir, 'rb') as f:
        first_key = SigningKey.from_pem(f.read())

    with open(second_key_dir, 'rb') as f:
        second_key = SigningKey.from_pem(f.read())

    signature_1 = first_key.sign(common_head_content, hashfunc=hashlib.sha256)
    signature_2 = second_key.sign(section_content, hashfunc=hashlib.sha256)

    signature_1_bin = bytearray(sizeof(upg_ecc_sign))
    signature = upg_ecc_sign.from_buffer(signature_1_bin)
    signature_1_bin[0:sizeof(signature.r) + sizeof(signature.s)] = signature_1
    signature_2_bin = bytearray(sizeof(upg_ecc_sign))
    signature = upg_ecc_sign.from_buffer(signature_2_bin)
    signature_2_bin[0:sizeof(signature.r) + sizeof(signature.s)] = signature_2

    return (signature_1_bin, signature_2_bin)
예제 #12
0
def load_keys():
    '''
    Loads the keys from disk or creates a new key pair if that is needed.
    '''
    if not os.path.isfile(sk_file):
        return create_reg_keys()

    sk = SigningKey.from_pem(open(sk_file).read())
    vk = sk.get_verifying_key()

    return sk,vk
예제 #13
0
 def test_sign(self):
     pem = '-----BEGIN EC PRIVATE KEY-----\nMHQCAQEEICg7E4NN53YkaWuAwpoqjfAofjzKI7Jq1f532dX+0O6QoAcGBSuBBAAK\noUQDQgAEjZcNa6Kdz6GQwXcUD9iJ+t1tJZCx7hpqBuJV2/IrQBfue8jh8H7Q/4vX\nfAArmNMaGotTpjdnymWlMfszzXJhlw==\n-----END EC PRIVATE KEY-----\n'
     signed = utils.sign("message", pem)
     sk = SigningKey.from_pem(pem)
     vk = sk.get_verifying_key()
     print(signed)
     signed = binascii.unhexlify(signed)
     vk.verify(signed,
               "message".encode(),
               hashfunc=hashlib.sha256,
               sigdecode=ecdsaUtil.sigdecode_der)
예제 #14
0
    def key_import(self, private_keyfile_path, public_keyfile_path):
        self.logger.info('key_import(%s, %s)', private_keyfile_path,
                         public_keyfile_path)

        with open(public_keyfile_path, 'r') as f:
            self.public_key = VerifyingKey.from_pem(f.read())

        with open(private_keyfile_path, 'r') as f:
            self.private_key = SigningKey.from_pem(f.read())

        self.key_register(self.public_key)
예제 #15
0
def convert_map_to_token_files(mapfile, keyfile, outfile, method='sign'):
    token_map = read_token_map(mapfile)

    if method == 'sign':
        with open(keyfile) as fh:
            signing_key = SigningKey.from_pem(fh.read())
    else:
        with open(keyfile, 'rb') as fh:
            signing_key = fh.read()

    with open(outfile, 'wb') as wfh:
        convert_map_to_token(token_map, signing_key, wfh, method)
예제 #16
0
def load_keystore(file_path: str = None, password: str = None):
    if file_path and password:
        try:
            with open(file_path, 'rb') as f:
                enc = f.read()

            cipher = AESCipher(password.encode())
            pem = cipher.decrypt(enc).decode()
            private_key = SigningKey.from_pem(pem)
            return private_key.to_string()
        except Exception as e:
            print('Wrong Password')
예제 #17
0
 def importarChavePrivada(self, chave):
     try:
         if isinstance(chave, io.IOBase):
             _arq = open(chave, "rb")
             chavePrivada = SigningKey.from_pem(_arq.read())
         elif isinstance(chave, str):
             chavePrivada = SigningKey.from_string(bytearray.fromhex(chave))
         return chavePrivada
     except IOError:
         print("Arquivo inexistente")
     finally:
         _arq.close()
예제 #18
0
 def load_keys(self):
     # load keys and address from existed files
     if os.path.exists('database/pri_key.pem') is not True \
         or os.path.exists('database/pub_key.pem') is not True \
         or os.path.exists('database/address.pkl') is not True:
         self.generate_keys()
     else:
         self.pri_key = SigningKey.from_pem(open('database/pri_key.pem').read())
         self.pub_key = VerifyingKey.from_pem(open('database/pub_key.pem').read())
         with open('database/address.pkl', 'rb') as file:
             self.address = pickle.load(file)
         print ('Current wallet address: %s'%self.address)
예제 #19
0
    def _gen_sig_dct(self, sdkappid, pri_key, identifier, expire=None):
        sig_dct = self._create_dct(sdkappid, pri_key, identifier, expire)
        fix_str = self._encode_to_fix_str(sig_dct)

        pk_loaded = SigningKey.from_pem(pri_key)
        sig_field = pk_loaded.sign(fix_str,
                                   hashfunc=hashlib.sha256,
                                   sigencode=util.sigencode_der)
        sig_field_base64 = base64.b64encode(sig_field)
        sig_dct['TLS.sig'] = sig_field_base64

        return sig_dct
예제 #20
0
def pem_to_privkey(pem):
    """ Get private key from given PEM encoded private key format.

    Args:
        pem (bytes): Private key in base64 encoded PEM format.

    Return:
        str: Hex encoded 32Byte secret exponent
    """
    sk = SigningKey.from_pem(pem)
    assert (sk.curve.openssl_name == 'secp256k1')
    return b2h(sk.to_string())
예제 #21
0
def ComputeSignature(file):
    sk = SigningKey.from_pem(open(args.privateKey).read())
    vk = sk.get_verifying_key()
    open("public.pem","w").write(vk.to_pem())
    sig = sk.sign(data=ReadMessageForSign(file),hashfunc=hashlib.sha256)
    signerHash = hashlib.sha256()
    for c in vk.to_string():
        signerHash.update(c.encode('hex'))  
    L = list(signerHash.hexdigest())
    signerInfo =""
    for x in range(48,64):
        signerInfo+=L[x]
    return [signerInfo,sig]
예제 #22
0
def read_sign1_key(keyfile):
    try:
        key = SigningKey.from_pem(open(keyfile, 'rb').read())
    except Exception as e:
        signing_key_error = str(e)

        try:
            key = VerifyingKey.from_pem(open(keyfile, 'rb').read())
        except Exception as e:
            verifying_key_error = str(e)

            msg = 'Bad key file "{}":\n\tpubkey error: {}\n\tprikey error: {}'
            raise ValueError(msg.format(keyfile, verifying_key_error, signing_key_error))
예제 #23
0
파일: keys.py 프로젝트: samken600/3YP
def load(path):
    with open(path, 'rb') as f:
        pem = f.read()
    try:
        key = RSA.importKey(pem)
        if key.n.bit_length() != 2048:
            raise Exception("Unsupported RSA bit length, only 2048 supported")
        return RSA2048(key)
    except ValueError:
        key = SigningKey.from_pem(pem)
        if key.curve.name != 'NIST256p':
            raise Exception("Unsupported ECDSA curve")
        return ECDSA256P1(key)
예제 #24
0
def test_pem():
    privkeyfile = "bin/0x2de5c210370daef452eb610af76c3a293ae1661f.pem.save"
    with open(privkeyfile) as f:
        p = f.read()
        print("pem file:", p)
        key = SigningKey.from_pem(p)
        print("privkey : ", encode_hex(key.to_string()))

        ac2 = Account.from_key(encode_hex(key.to_string()))
        print("pubkey: ", ac2.publickey)
        print("address: ", ac2.address)
        toPem = SigningKey.to_pem(key)
        print("pem from key", toPem)
예제 #25
0
    def __generate_signature(self):
        if os.path.isfile('my_sign_tx'):
            with open("my_sign_tx", "r") as f:
                self.signature = f.read()

            return

        line = self.public_key.encode()
        sk = SigningKey.from_pem(self.private_key)
        self.signature = sk.sign(line).hex()

        with open("my_sign_tx", "w+") as f:
            f.write(self.signature)
예제 #26
0
def main():
    i = random.randint(1, USER_NO)
    # sk_filename = sys.argv[1]
    sk_filename = "p" + str(i) + ".pem"
    sk = SigningKey.from_pem(open(sk_filename).read())

    j = i
    while j == i:
        j = random.randint(1, USER_NO)
    receiver_filename = "p" + str(j) + ".pem"
    rec = SigningKey.from_pem(open(receiver_filename).read())
    amount = random.randint(1, 20)

    vk = sk.get_verifying_key()
    sender = base64.b64encode(vk.to_string())
    receiver_key = rec.get_verifying_key()
    receiver = base64.b64encode(receiver_key.to_string())
    txid = uuid.uuid4().hex
    timestamp = time.time()

    transaction = {
        "txid": txid,
        "sender": str(sender, encoding="utf-8"),
        "receiver": str(receiver, encoding="utf-8"),
        "timestamp": timestamp,
        "amount": amount
    }
    print(transaction)
    signature = sk.sign(json.dumps(transaction).encode('utf-8'))
    data = {
        "transaction": transaction,
        "signature": str(base64.b64encode(signature), encoding="utf-8")
    }

    # try:
    assert vk.verify(signature, json.dumps(transaction).encode('utf-8'))
    db.execute(
        "INSERT INTO transactions (data, txid, timestamp) VALUES (%s, %s, %s)",
        json.dumps(data), txid, int(timestamp))
예제 #27
0
    def key_import(self, private_keyfile_path, public_keyfile_path):
        self.logger.info(
            'key_import(%s, %s)',
            private_keyfile_path,
            public_keyfile_path)

        with open(public_keyfile_path, 'r') as f:
            self.public_key = VerifyingKey.from_pem(f.read())

        with open(private_keyfile_path, 'r') as f:
            self.private_key = SigningKey.from_pem(f.read())

        self.key_register(self.public_key)
예제 #28
0
def check_ecc(cert,key_str):
    detail = re.findall("\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-[\w|\W]+?(?:\-\-\-\-\-END CERTIFICATE\-\-\-\-\-)",cert)
    u_str = str(uuid.uuid1())
    cert_path = "{}.pem".format(u_str)
    file_path = "/Application/bermuda/conf/rsa/"+cert_path
    with open(file_path,'w') as f_cert:
        f_cert.write(detail[0])
    pu_key = run_openssl("x509 -outform PEM -in {} -pubkey -noout".format(file_path))
    # os.remove(file_path)
    sk2 = SigningKey.from_pem(key_str)
    vk = VerifyingKey.from_pem(pu_key)
    signature = sk2.sign(b"message")
    return vk.verify(signature, b"message")
def get_signing_key():
    if not os.path.exists(private):
        print('Creating private key %r' % private)
        sk0 = SigningKey.generate(curve=curve)
        with open(private, 'w') as f:
            f.write(sk0.to_pem())

        vk = sk0.get_verifying_key()
        with open(public, 'w') as f:
            f.write(vk.to_pem())
    pem = open(private).read()
    sk = SigningKey.from_pem(pem)
    return sk
예제 #30
0
def init_carte(name, surname):
    global compteurparticipant, logger
    name = name + " "
    surname = surname + " "
    namehex = name.encode("UTF-8").hex()
    while len(namehex) < 24:
        namehex = "0" + namehex

    surnamehex = surname.encode("UTF-8").hex()
    while len(surnamehex) < 24:
        surnamehex = "0" + surnamehex

    compteur_participant_hex = "{:x}".format(compteurparticipant)
    while len(compteur_participant_hex) < 10:
        compteur_participant_hex = "0" + compteur_participant_hex
    pin = generatepin()
    print("Voici le PIN du Client: " + str(pin))
    pinhex = "{:x}".format((int)(pin[:2])) + "{:x}".format((int)(pin[2:]))
    while len(str(pinhex)) < 4:
        pinhex = "0" + pinhex
    # Génération de la pair de clés ECDSA pour signer la carte
    # clesecrete = ecdsa.SigningKey.generate(
    #     curve=ecdsa.NIST256p)  # Géneration clé secrete carte
    # clesecrete_string = (clesecrete.to_string()).hex()
    # clepublic = clesecrete.get_verifying_key()  # Génération clé publique carte
    # clepubcarte_string = (clepublic.to_string()).hex()
    # message = namehex+surnamehex+str(compteurparticipant)  # données a signer
    # signdata = clesecrete.sign(message.encode("utf-8"))  # Exemple signature message
    # print("Secret:" + str(signdata))
    # file_ = open("secretpubliccarte", 'w')
    # file_.write(clepubcarte_string + "\n")
    # file_.close()

    skcarte = SigningKey.from_pem(open("client/privatecarte.pem").read())

    message = namehex + surnamehex + compteur_participant_hex  # données a signer
    signdata = skcarte.sign(
        message.encode("utf-8"))  # Exemple signature message
    # sktpe = SigningKey.generate() #generation clef privée
    # vktpe = sk.get_verifying_key() #génération clef publique
    # open("privatetpe.pem","w").write(sk.to_pem())
    # open("publictpe.pem","w").write(vk.to_pem())
    hex_sign = signdata.hex()
    #print(len(pinhex+surnamehex+namehex+compteur_participant_hex+hex_sign))
    # reponse = subprocess.check_output(['java', '-jar', '/home/grs/JavaCard/GlobalPlatformPro/gp.jar', '-install',
    #                                    '../Festival221.cap', '--param', pinhex+surnamehex+namehex+compteur_participant_hex+hex_sign])
    #print(hex_sign)
    #print(message)
    command = 'java -jar /home/grs/JavaCard/GlobalPlatformPro/gp.jar --install ../Javacard_MSI_P8/Festival221.cap --param ' + pinhex + surnamehex + namehex + compteur_participant_hex + hex_sign

    os.system(command)
예제 #31
0
def sign_firmware_for_version(sk_name,
                              hex_file,
                              APPLICATION_END_PAGE,
                              PAGES=128):
    # Maybe this is not the optimal module...

    import base64
    import binascii
    from hashlib import sha256

    from ecdsa import SigningKey
    from intelhex import IntelHex

    sk = SigningKey.from_pem(open(sk_name).read())
    fw = open(hex_file, "r").read()
    fw = base64.b64encode(fw.encode())
    fw = helpers.to_websafe(fw.decode())
    ih = IntelHex()
    ih.fromfile(hex_file, format="hex")
    # start of firmware and the size of the flash region allocated for it.
    # TODO put this somewhere else.
    START = ih.segments()[0][0]
    # keep in sync with targets/stm32l432/src/memory_layout.h
    PAGE_SIZE = 2048
    END = (0x08000000 + ((PAGES - APPLICATION_END_PAGE) * PAGE_SIZE)) - 8

    ih = IntelHex(hex_file)
    # segs = ih.segments()
    arr = ih.tobinarray(start=START, size=END - START)

    im_size = END - START

    print("im_size: ", im_size)
    print("firmware_size: ", len(arr))

    byts = (arr).tobytes() if hasattr(arr, "tobytes") else (arr).tostring()
    h = sha256()
    h.update(byts)
    sig = binascii.unhexlify(h.hexdigest())
    print("hash", binascii.hexlify(sig))
    sig = sk.sign_digest(sig)

    print("sig", binascii.hexlify(sig))

    sig = base64.b64encode(sig)
    sig = helpers.to_websafe(sig.decode())

    # msg = {'data': read()}
    msg = {"firmware": fw, "signature": sig}
    return msg
예제 #32
0
def get_key():
    # 파일로부터 개인키, 공개키 읽어서 리턴

    if (not os.path.exists(PRI_KEY_PATH)):
        print("Generate keys...")
        generate_key()

    if (os.path.exists(PRI_KEY_PATH)):
        pri_key = SigningKey.from_pem(
            open(PRI_KEY_PATH, encoding='utf-8').read())
        pub_key = pri_key.get_verifying_key()
        return pri_key, pub_key

    return '', ''
예제 #33
0
def load_keys(btc_addr):
    """ Loads an elliptic curve key pair in PEM format from disk. Keys are stored in their proper objects from the ecdsa
    python library (SigningKey and VerifyingKey respectively)

    :param btc_addr: Bitcoin address associated to the public key of the key pair.
    :type btc_addr: str
    :return: ecdsa key pair as a tuple.
    :rtype: SigningKey, VerifyingKey
    """

    sk_pem = open(btc_addr + '/sk.pem', "r").read()
    pk_pem = open(btc_addr + '/pk.pem', "r").read()

    return SigningKey.from_pem(sk_pem), VerifyingKey.from_pem(pk_pem)
예제 #34
0
def load(path):
    with open(path, 'rb') as f:
        pem = f.read()
    if len(pem) == 16:
        if "AES_CBC" in path:
            return AES_CBC(pem)
        else:
            return AES_GCM(pem)
    else:
        key = SigningKey.from_pem(pem)
        if key.curve.name == 'NIST256p':
            return ECDSA256P1(key)
        else:
            raise Exception("Unsupported")
예제 #35
0
    def get_key_pair():
        """
        若保存密钥对的文件存在则从文件中读取秘钥,否则重新生成
        :return:
        """
        if os.path.exists(Const.PVT_KEY_LOC) and os.path.exists(
                Const.PUB_KEY_LOC):
            pvt_key = SigningKey.from_pem(open(Const.PVT_KEY_LOC).read())
            pub_key = VerifyingKey.from_pem(open(Const.PUB_KEY_LOC).read())

        else:
            pvt_key, pub_key = Signature.gen_key_pair()

        return pvt_key, pub_key
예제 #36
0
def get_signing_key() -> SigningKey:
    if not os.path.exists(private):
        print("Creating private key %r" % private)
        sk0 = SigningKey.generate(curve=curve)
        with open(private, "w") as f:
            f.write(sk0.to_pem())

        vk = sk0.get_verifying_key()
        with open(public, "w") as f:
            f.write(vk.to_pem())

    with open(private) as f:
        pem = f.read()
    sk = SigningKey.from_pem(pem)
    return cast(SigningKey, sk)
예제 #37
0
    def __post_init__(self):
        """Initialize, Serialize and Sign"""

        if isinstance(self._key, bytes):
            self._sk = SigningKey.from_pem(self._key)
        elif isinstance(self._key, str):
            with open(self._key, "rb") as fp:
                self._sk = SigningKey.from_pem(fp.read())
        else:
            raise ValueError(
                "_key must be a str with the path or a bytes object with the raw key"
            )

        self._qs = self.serialize()
        self._sig = self.sign()

        del self._sk
        self._key = None
        self.teamId = None
        self.keyId = None

        self.url = f"{self.BASE_URL}{self._sig}"

        del self._sig
예제 #38
0
    def generate_key_pair(self):
        separator = "="
        key_dir = None
        with open("/opt/BarbiE/env.properties") as f:
            for line in f:
                if separator in line:
                    name, value = line.split(separator)
                    if name.strip() == "KEY_PAIR_DIR":
                        key_dir = value.strip()
        pub_key_path = os.path.join(key_dir, "public_key.pem")
        priv_key_path = os.path.join(key_dir, "private_key.pem")
        if not os.path.exists(pub_key_path):
            priv_key = SigningKey.generate(curve=NIST256p)
            pub_key = priv_key.get_verifying_key()
            open(priv_key_path,"w").write(priv_key.to_pem())
            open(pub_key_path,"w").write(pub_key.to_pem())
        else:
            priv_key = SigningKey.from_pem(open(priv_key_path).read())
            pub_key = VerifyingKey.from_pem(open(pub_key_path).read())

        pk64 = pub_key.to_string()
        pk_x, pk_y = pk64[:len(pk64)/2], pk64[len(pk64)/2:]
        hex_priv_key = priv_key.to_string()
        hex_sk = hex_priv_key.encode('hex')

        pk_x = pk_x.encode('hex')
        pk_y = pk_y.encode('hex')
        hex_priv_key_out = [hex_sk[i:i + 2]for i in range(0, len(hex_sk), 2)]
        pk_x_out = [pk_x[i:i + 2] for i in range(0,len(pk_x), 2)]
        pk_y_out = [pk_y[i:i + 2] for i in range(0,len(pk_y), 2)]

        pk_x_out.reverse()
        pk_y_out.reverse()

        pub_key = ""
        for i in range(len(pk_x_out)):
            pub_key = pub_key + pk_x_out[i]
        for i in range(len(pk_y_out)):
            pub_key = pub_key + pk_y_out[i]
        hex_priv_key_out.reverse()
        priv_key = ""
        for i in range(len(hex_priv_key_out)):
            priv_key = priv_key + hex_priv_key_out[i]

        pub_key = base64.b64encode(pub_key + '\0')
        priv_key = base64.b64encode(priv_key + '\0')

        return pub_key , priv_key
def get_hashes(private_signing_key_file, public_key_files):
    hashes = list()
    with open(private_signing_key_file, 'r') as fn:
        hashes.append(
            sha256(
                SigningKey.from_pem(
                    fn.read()).get_verifying_key().to_string()).digest()[:16])
        verbose_print("hash: " + hashes[-1].hex())
    for fn in public_key_files:
        verbose_print("Getting hash of %s" % fn)
        with open(fn, 'rb') as f:
            hashes.append(
                sha256(VerifyingKey.from_pem(
                    f.read()).to_string()).digest()[:16])
        verbose_print("hash: " + hashes[-1].hex())
    return hashes
예제 #40
0
def extract_iat_from_cose(keyfile, tokenfile, keep_going=False):
    if keyfile:
        try:
            sk = SigningKey.from_pem(open(keyfile, 'rb').read())
        except Exception as e:
            msg = 'Bad key file "{}": {}'
            raise ValueError(msg.format(keyfile, e))
    else:  # no keyfile
        sk = None

    try:
        with open(tokenfile, 'rb') as wfh:
            return get_cose_payload(wfh.read(), sk)
    except Exception as e:
        msg = 'Bad COSE file "{}": {}'
        raise ValueError(msg.format(tokenfile, e))
예제 #41
0
def calculate_signatute(data):
    print()
    print('--- CALCULATE SIGNATURE ---')
    DIR = os.path.dirname(sys.argv[0])
    PRIVATE = join(DIR, 'certs', 'ecprivkey.pem')
    PUBLIC = join(DIR, 'certs', 'ecpubkey.pem')
    sk = SigningKey.from_pem(open(PRIVATE).read(), hashfunc=hashlib.sha256)
    vk = VerifyingKey.from_pem(open(PUBLIC).read())
    signature = sk.sign(data, hashfunc=hashlib.sha256)
    try:
        vk.verify(signature, data, hashfunc=hashlib.sha256)
        print("    signature ok")
    except BadSignatureError:
        print("[ERROR] BAD SIGNATURE")
        exit(1)
    return signature
예제 #42
0
파일: encryptator.py 프로젝트: magarcia/C
def send_message(args):
    from ecdsa import SigningKey
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric import padding

    backend = default_backend()
    key_size = 2048

    message = args.message.read()

    public_key = serialization.load_pem_public_key(
        args.publicKey.read(),
        backend=backend
    )

    key = generate_key()

    key_enc = public_key.encrypt(
        key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None
        )
    )

    signatureKey = SigningKey.from_pem(args.signatureKey.read())
    signature = sign(signatureKey, message)

    iv, encrypted = encrypt(key, message + signature)

    name = os.path.basename(args.message.name)

    with open('%s.enc' % name, 'wb') as output:
        output.write(key_enc + iv + encrypted)
예제 #43
0
 def __init__(self):
     self.sk = {}
     # Loading signature keys to memory
     for keyid, private_key in settings.CUP_PEM_KEYS.iteritems():
         self.sk[keyid] = SigningKey.from_pem(open(private_key).read())
예제 #44
0
def sign_verification_record(signatory,
                             prior_block_hash,
                             lower_hash,
                             public_key_string,
                             private_key_string,
                             block_id,
                             phase,
                             origin_id,
                             verification_ts,
                             public_transmission,
                             verification_info):
    """
    Sign a (block) verification record
    :param signatory: Name or identifier of the signing party (the caller)
    :param prior_block_hash: Hash of the prior block (verification record with the same origin_id, phase, and signatory)
    :param lower_hash: Hash of the lower phase verification record
    :param public_key_string: hashed and inserted into signature block for later validation
    :param private_key_string: private key used for generating signature
    :param block_id: Verification record block ID
    :param phase: Verification record phase
    :param origin_id: ID of the origin node (phase 1 node)
    :param verification_ts:
    :param public_transmission:
    :param verification_info: Phase specific information to be included in the signature
        - phase_1: list of approved transactions (dictionaries)
        - phase_2: valid_tx ID list, invalid_tx ID list, business ID, deploy_location
        - phase_3: phase_2 count, business_diversity list, deploy_loc_diversity list
        - phase_4: Nothing (notary function only)
        - phase_5: One of:
            - transaction
            - verification_record
            - hash
            - arbitrary string
    :return: verification record with assembled signature field
    """

    ecdsa_signing_key = SigningKey.from_pem(private_key_string)
    block_info = {}
    signature_ts = int(time.time())
    hashed_items = []

    # append prior_block_hash and lower_hash
    hashed_items.append(prior_block_hash)
    hashed_items.append(lower_hash)

    # append my signing info for hashing
    hashed_items.append(signatory)
    hashed_items.append(signature_ts)
    hashed_items.append(public_key_string)

    # append given info for hashing
    hashed_items.append(block_id)
    hashed_items.append(phase)
    hashed_items.append(origin_id)
    hashed_items.append(verification_ts)

    # append verification_info hash for hashing
    hashed_items.append(deep_hash(verification_info))

    verification_hash = final_hash(hashed_items)

    signature = ecdsa_signing_key.sign(verification_hash)
    digest = signature.encode('base64')

    verification_record = {
        "verification_ts": int(time.time()),
        "block_id": block_id,
        "origin_id": origin_id,
        "phase": int(phase),
        "prior_hash": prior_block_hash,
        "lower_hash": lower_hash,
        "public_transmission": public_transmission,
        "verification_info": verification_info  # special phase info
    }

    assemble_sig_block(verification_record, signatory, public_key_string, digest, verification_hash, signature_ts)

    block_info['block_id'] = block_id
    block_info['phase'] = int(phase)
    block_info['verification_record'] = verification_record

    return block_info
예제 #45
0
def certificateRevocation():
    print art
    print "\nCertificate Revocation Script - Block SSL\n"
    print "In which of your addresses do you still have access? default: [1]\n"
    print "\t1. All of the addresses. (Generation, Certificate, Revocation)\n"
    print "\t2. Only Certificate address.\n"
    print "\t3. Only Revocation address.\n"
    print "\t4. Revocation and Generation addresses.\n"
    ans = raw_input()
    if ans == "1" or ans == "" or ans == " " or ans == "2":
        address = open("Cert_Address.txt", "r").read()
        address = address.strip()
        if address[1] == "x":
            address = address.split("0x")[1]
        url = "https://api.blockcypher.com/v1/eth/main/addrs/" + address + "/balance"
        try:
            r = requests.get(url)
            balance = r.json()
            balance = str(balance)
            x = 1
            i = 1
            final_balance = ""
            balance = balance.split("\'final_balance\':")[1]
            while x == 1:
                if balance[i] == "L" or balance[i] == ",":
                    x += 1
                else:
                    final_balance = final_balance + balance[i]
                    i += 1

            print "\nYour Certificate address balance is: " + final_balance
            final_balance = int(final_balance)
            #Opening Generation private key from pem file
            if os.path.isfile('./Certificate_Private.pem'):
                print "\nCertificate Private Key file exists."
                sk = SigningKey.from_pem(open("Certificate_Private.pem").read())
                sk_string = sk.to_string()
                sk = str(sk_string)
                sk = sk.encode("hex")
            elif os.path.isfile('./Certificate_Private.pem.enc'):
                print "\nCertificate Private Key encoded file exists."
                decrypt_file(key, "Certificate_Private.pem.enc")
                print "\nDecrypting Certificate Private Key..."
                print "Saving to Certificate_Private.pem..."
                sk = SigningKey.from_pem(open("Certificate_Private.pem").read())
                sk_string = sk.to_string()
                sk = str(sk_string)
                sk = sk.encode("hex")
            else:
                print "\nCertificate Private Key does not exist."
                print "\nPlease place the .pem file in the script directory.\n"
                sys.exit()
        except ValueError, e:
            raise Exception('Invalid response from Blockcypher.')
        if ans == "1" or ans == "" or ans == " ":
            recepient_address = open("Gen_Address.txt", "rb").read()
            ans3 = raw_input("Which is your revocation reason?\n")
            data = "R1: " + ans3
        else:
            recepient_address = raw_input("Give the address that you want to sent the certificate balance, for revocation purposes:\n")
            data = "R2: No access to Generation address"
            #todo - check if the address is correct
        try:
            nonce = 100
            gas_price = 10000000000
            gas_limit = 22000
            value = final_balance
            token = "48193195898942febdc67d60316ad204"
            recipient_address = recipient_address.strip('\n')
            unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, recipient_address, value, data).sign(sk))
            signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')
            os.system("curl -sd \'{\"tx\":\"" + signedtx + "\"}\' https://api.blockcypher.com/v1/eth/main/txs/push?token=" + token)
        except Exception:
            print "\nNo balance in your Certificate address.\n"
            print "If the Certificate address has 0 balance, it has been already been revoced.\n"
예제 #46
0
def sign_transaction(signatory,
                     private_key_string,
                     public_key_string,
                     transaction,
                     log=logging.getLogger(__name__)):
    """
    Sign a transaction
    :param signatory: Name or identifier of the signing party (the caller)
    :param private_key_string:
    :param public_key_string:
    :param transaction: Transaction to sign
    :param log:
    :return: Transaction with assembled signature field
    """
    hashed_items = []

    child_signature = None
    if "signature" in transaction:
        child_signature = transaction["signature"]
        log.info("Saving the child signature:  %s" % str(child_signature))
        # add old signature digest to hash list if there was one
        if 'digest' in child_signature:
            log.info("Adding signature digest to hash list")
            hashed_items.append(child_signature["digest"])

    signature_ts = int(time.time())

    log.info("Loading private key from string")
    ecdsa_signing_key = SigningKey.from_pem(private_key_string)

    # add transaction header info to hashed_items
    transaction_header = transaction["header"]
    for header_key in transaction_header:
        if header_key not in non_included_txn_items:
            hashed_items.append(transaction_header[header_key])

    # append my signing info for hashing
    hashed_items.append(signatory)
    hashed_items.append(signature_ts)
    hashed_items.append(public_key_string)

    log.info("Creating stripped hash")
    stripped_hash = final_hash(hashed_items)
    log.debug("stripped_transaction_hash=%s" % stripped_hash)

    # put hashed transaction payload back and append to hashed_items
    if transaction["payload"]:
        log.info("Hashing payload")
        hashed_items.append(deep_hash(transaction["payload"]))
        # generate hash with with hashed payload included
        log.info("Generating hash")
        hash = final_hash(hashed_items)
    else:
        hash = stripped_hash

    # merge stripped_hash and hash to send for signing
    log.info("Merging stripped and full hash")
    merged_hash = merge_hashes(stripped_hash, hash)

    # sign merged hash
    log.info("Signing merged hash")
    signature = ecdsa_signing_key.sign(str(merged_hash))
    log.info("Base64 encoding the signature")
    digest = signature.encode('base64')

    assemble_sig_block(transaction, signatory, public_key_string, digest, hash, signature_ts, stripped_hash,
                       child_signature)

    return transaction
예제 #47
0
def certificateUpdate():
    print art
    print "\nCertificate Update Script - Block SSL\n"
    # create a key pair or use the old one
    ans = raw_input("Do you have your old keys.key file with your key pair? [Y]es [N]o, default: [Y]\n")
    if ans == "n" or ans == "N":
        k = crypto.PKey()
        k.generate_key(crypto.TYPE_RSA, 4096)
        print "Creating a new key pair:"
        print "Warning: This is a pseudo-random generation.\n"
    else:
        print "Place your keys.key file in the scripts directory.\n"
        k = crypto.PKey()
        with open("keys.key", "r") as k:
            k = crypto.load_privatekey(crypto.FILETYPE_PEM, k.read())

    # create a self-signed cert
    cert = crypto.X509()
    createCert(k, cert)

    open("certificate.crt", "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    print "\nCertificate created in file: certificate.crt"
    if ans == "n" or ans == "N":
        open("keys.key", "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
        print "\nKeys saved in file: keys.key\n"

    ans2 = raw_input("Do you want to send your certificate to the blockchain? [Y]es [N]o, default: [Y]")
    if ans2 == "Y" or ans2 == "y" or ans2 == "" or ans2 == " ":
        i = 2
        mode = "UC: "
        #Hashing of the certificate
        f = open("certificate.crt", "rb") #read file in binary mode
        fr = f.read()
        cert_hash = hashlib.sha256() #use the SHA256 hashing algorithm
        cert_hash.update(fr)
        data = cert_hash.hexdigest()
        nonce = 100
        gas_price = 10000000000
        gas_limit = 22000
        value = 1000000000000000000
        token = "48193195898942febdc67d60316ad204"
        print "\nYour Certificate hash is: ", data
        data = mode + data
        print "\nAdding to OP_RETURN..."
        #Opening Generation private key from pem file
        if os.path.isfile('./Certificate_Private.pem'):
            print "\nCertificate Private Key file exists."
            sk = SigningKey.from_pem(open("Certificate_Private.pem").read())
            sk_string = sk.to_string()
            sk = str(sk_string)
            sk = sk.encode("hex")
        elif os.path.isfile('./Certificate_Private.pem.enc'):
            print "\nCertificate Private Key encoded file exists."
            decrypt_file(key, "Certificate_Private.pem.enc")
            print "\nDecrypting Certificate Private Key..."
            print "Saving to Certificate_Private.pem..."
            sk = SigningKey.from_pem(open("Certificate_Private.pem").read())
            sk_string = sk.to_string()
            sk = str(sk_string)
            sk = sk.encode("hex")
        else:
            print "\nCertificate Private Key does not exist."
            print "\nPlease place the file in the script directory or run -i option for a new key pair.\n"
            sys.exit()
        try:
            recipient_address = open("Cert_Address.txt", "rb").read()
            recipient_address = recipient_address.strip('\n')
            unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, recipient_address, value, data).sign(sk))
            signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')
            os.system("curl -sd \'{\"tx\":\"" + signedtx + "\"}\' https://api.blockcypher.com/v1/eth/main/txs/push?token=" + token)
        except Exception:
            print "\nNo balance in your Certificate address.\n"
            print "Please first run the -cc or the -u script.\n"
    sys.exit()
예제 #48
0
         nonce = 100
         gas_price = 10000000000
         gas_limit = 22000
         value = final_balance
         token = "48193195898942febdc67d60316ad204"
         recipient_address = recipient_address.strip('\n')
         unencoded_tx = rlp.encode(transactions.Transaction(nonce, gas_price, gas_limit, recipient_address, value, data).sign(sk))
         signedtx = '0x' + codecs.encode(unencoded_tx, 'hex').decode('utf-8')
         os.system("curl -sd \'{\"tx\":\"" + signedtx + "\"}\' https://api.blockcypher.com/v1/eth/main/txs/push?token=" + token)
     except Exception:
         print "\nNo balance in your Certificate address.\n"
         print "If the Certificate address has 0 balance, it has been already been revoced.\n"
 elif ans == "3" or ans == "4":
     if os.path.isfile('./Revocation_Private.pem'):
         print "\nRevocation Private Key file exists."
         sk = SigningKey.from_pem(open("Revocation_Private.pem").read())
         sk_string = sk.to_string()
         sk = str(sk_string)
         sk = sk.encode("hex")
     elif os.path.isfile('./Revocation_Private.pem.enc'):
         print "\nRevocation Private Key encoded file exists."
         decrypt_file(key, "Revocation_Private.pem.enc")
         print "\nDecrypting Revocation Private Key..."
         print "Saving to Revocation_Private.pem..."
         sk = SigningKey.from_pem(open("Revocation_Private.pem").read())
         sk_string = sk.to_string()
         sk = str(sk_string)
         sk = sk.encode("hex")
     else:
         print "\nRevocation Private Key does not exist."
         print "\nPlease place the .pem file in the script directory.\n"
예제 #49
0
def get_compressed_public_key_from_pem(pem):
    vks = SigningKey.from_pem(pem).get_verifying_key().to_string()
    bts = binascii.hexlify(vks)
    compressed = compress_key(bts)
    return compressed
예제 #50
0
def sign(message, pem):
    message = message.encode()
    sk = SigningKey.from_pem(pem)
    signed = sk.sign(message, hashfunc=hashlib.sha256, sigencode=ecdsaUtil.sigencode_der)
    return binascii.hexlify(signed).decode()