Exemplo n.º 1
0
def new_wallet():
 
    sk = SigningKey.generate(curve=ecdsa.SECP256k1)
    vk = sk.get_verifying_key()
    
    open("private.pem","wb").write(sk.to_pem())
    open("public.pem" ,"wb").write(vk.to_pem()) 
    
    ssk=sk.to_string() 
    svk=vk.to_string() 
    
    print(ssk)
    print(svk)

    fsk = SigningKey.from_pem(sk.to_pem())
    fvk = VerifyingKey.from_pem(vk.to_pem())
    
    print(fsk)
    print(fvk)
    
    fpemsk = SigningKey.from_pem(open("private.pem").read())
    print(fpemsk.to_string())
    
    fpemvk = VerifyingKey.from_pem(open("public.pem").read())
    print(fpemvk.to_string())
        
    response = {  
        'private_key': binascii.hexlify(ssk).decode('utf-8'),
        'public_key' : binascii.hexlify(svk).decode('utf-8')     
    }
    
    return jsonify(response), 200
Exemplo n.º 2
0
def getKeys():
    public_key = {}
    private_key = {}
    try:
        public_key = VerifyingKey.from_pem(open("public.pem").read())
        private_key = SigningKey.from_pem(open("private.pem").read())
    except:
        generateKeys()
        public_key = VerifyingKey.from_pem(open("public.pem").read())
        private_key = SigningKey.from_pem(open("private.pem").read())
    return public_key, private_key
Exemplo n.º 3
0
def loadpubstr(pemstring):
    """
    Load a public key from PEM string
    :param pemstring:
    :return:
    """
    return VerifyingKey.from_pem(pemstring)
Exemplo n.º 4
0
def call_from_files(public_key_path, message1_path, message2_path,
                    signature1_path, signature2_path, hash_alg):
    """

    :param public_key_path:
    :param message1_path:
    :param message2_path:
    :param signature1_path:
    :param signature2_path:
    :param hash_alg:
    :return:
    """
    pkey = get_file_content(public_key_path)
    msg1 = get_file_content(message1_path)
    msg2 = get_file_content(message2_path)
    sig1 = get_file_content(signature1_path)
    sig2 = get_file_content(signature2_path)

    # Transform PEM public key to python VerifyinKey type
    public_verification_key = VerifyingKey.from_pem(pkey.strip())

    # Launch exploit to try to get private key
    private_key = get_private_key(public_verification_key.curve,
                                  msg1.encode('utf-8'), sig1,
                                  msg2.encode('utf-8'), sig2,
                                  get_hash_function(hash_alg))

    return private_key
Exemplo n.º 5
0
def validate_signature(signature_block, log=logging.getLogger(__name__)):
    """
    Validates signature of verification record or transaction accounting for presence of
        "stripped_hash" in transaction signatures
    :param signature_block: dict of signature
    :param log: message logger
    :return: True on valid signature, False otherwise.
    """

    """ validate signature using provided stripped and full hashes """

    verifying_key = VerifyingKey.from_pem(signature_block["public_key"])

    log.info("Decoding the digest")
    decoded_digest = signature_block["signature"].decode('base64')

    log.info('Performing signature verification')
    # checking stripped hash if this is a transaction signature
    if "stripped_hash" in signature_block and signature_block['stripped_hash']:
        merged_hash = merge_hashes(signature_block["stripped_hash"], signature_block["hash"])
        verifying_key.verify(decoded_digest, str(merged_hash))
    else:
        verifying_key.verify(decoded_digest, str(signature_block["hash"]))
    # signature hash is valid
    return True
Exemplo n.º 6
0
def detect_key_type(pem_data):
    """ Positive Key type detection """

    try:
        RSA.importKey(pem_data)
        return KeyType.RSA
    except:
        pass

    try:
        VerifyingKey.from_pem(pem_data)
        return KeyType.ECC
    except:
        pass

    raise UnknownKeyType('Unable to guess Key type')
Exemplo n.º 7
0
 def _verify_wo_response_signature(self, wo_response,
                                   wo_res_verification_key):
     """
     Function to verify the work order response signature
     Parameters:
         @param wo_response - dictionary contains work order response
         as per Trusted Compute EEA API 6.1.2 Work Order Result Payload
         @param wo_res_verification_key - ECDSA/SECP256K1 public key
         used to verify work order response signature.
     Returns enum type SignatureStatus
     """
     worker_nonce = wo_response["workerNonce"]
     signature = wo_response['workerSignature']
     response_hash = self.calculate_response_hash(wo_response)
     try:
         _verifying_key = VerifyingKey.from_pem(wo_res_verification_key)
     except Exception as error:
         logger.error("Error in verification key of "
                      "work order response : %s",
                      error)
         return SignatureStatus.INVALID_VERIFICATION_KEY
     decoded_signature = crypto_utility.base64_to_byte_array(signature)
     try:
         sig_result = _verifying_key.verify_digest(decoded_signature,
                                                   response_hash,
                                                   sigdecode=sigdecode_der)
         if sig_result:
             return SignatureStatus.PASSED
     except Exception as er:
         if("Malformed formatting of signature" in str(er)):
             return SignatureStatus.INVALID_SIGNATURE_FORMAT
         return SignatureStatus.FAILED
Exemplo n.º 8
0
    def verify(self, verify_key_path):
        """Verify the package using a DER or PEM encoded public key"""
        if not HAVE_CRYPTO:
            raise Exception("ecdsa library not installed")

        raw_key_data = ""
        with open(verify_key_path, "rb") as f:
            raw_key_data = f.read()

        vk = None
        try:
            vk = VerifyingKey.from_der(raw_key_data)
        except:
            pass

        try:
            vk = VerifyingKey.from_pem(raw_key_data)
        except:
            pass

        if vk is None:
            raise Exception("Could not load public key")

        sig = self.pkg.read_signature()
        digest = self.pkg.read_digest()

        return vk.verify_digest(sig, digest, sigdecode=sigdecode_der)
Exemplo n.º 9
0
def verifyPublicCert(cert):
    assert cert
    pk = unpackCert(cert)
    msgBody = pk.get("identity") + pk.get("issued") + pk.get("version") + pk.get("publicKey")
    pubKey = VerifyingKey.from_pem(b64decode(pk.get("publicKey")))
    sig = b64decode(pk.get("signature"))
    return pubKey.verify(sig, msgBody)
Exemplo n.º 10
0
 def from_pem(pem: str):
     _verifyKey = EcdsaVerifyingKey.from_pem(string=pem)
     if _verifyKey.curve == curves.NIST256p:
         curve = 'r1'
     else:
         curve = 'k1'
     return PublicKey(_verifyKey, curve)
Exemplo n.º 11
0
def validate_signature(signature_block, log=logging.getLogger(__name__)):
    """
    Validates signature of verification record or transaction accounting for presence of
        "stripped_hash" in transaction signatures
    :param signature_block: dict of signature
    :param log: message logger
    :return: True on valid signature, False otherwise.
    """
    """ validate signature using provided stripped and full hashes """

    verifying_key = VerifyingKey.from_pem(signature_block["public_key"])

    log.info("Decoding the digest")
    decoded_digest = signature_block["signature"].decode('base64')

    log.info('Performing signature verification')
    # checking stripped hash if this is a transaction signature
    if "stripped_hash" in signature_block and signature_block['stripped_hash']:
        merged_hash = merge_hashes(signature_block["stripped_hash"],
                                   signature_block["hash"])
        verifying_key.verify(decoded_digest, str(merged_hash))
    else:
        verifying_key.verify(decoded_digest, str(signature_block["hash"]))
    # signature hash is valid
    return True
Exemplo n.º 12
0
    def __init__(self, path=os.getcwd()):
        """
        We load in the constructor the private and the public key
        """
        # We create the path for the private and the public key in the hard
        # drive
        private_path = os.path.normpath(os.path.join(path, "private.pem"))
        public_path = os.path.normpath(os.path.join(path, "public.pem"))

        # We get (or generate) the private key
        if (os.path.exists(private_path)):
            private_file = open(private_path, "rb")
            self.private = SigningKey.from_pem(private_file.read())
            private_file.close()
        else:
            self.private = SigningKey.generate()
            private_file = open(private_path, "wb")
            private_file.write(self.private.to_pem())
            private_file.close()

        # We get (or generate) the public key
        if (os.path.exists(public_path)):
            public_file = open(public_path, "rb")
            self.public = VerifyingKey.from_pem(public_file.read())
            public_file.close()
        else:
            self.public = self.private.get_verifying_key()
            public_file = open(public_path, "wb")
            public_file.write(self.public.to_pem())
            public_file.close()
Exemplo n.º 13
0
def add_to_ledger():
    if 'pub_key' not in request.form or 'sig' not in request.form:
        return jsonify({'error': 'need public key and its signature'})
    else:
        pub_key = request.form['pub_key']
        b64_sig = request.form['sig']
        sig = base64.b64decode(b64_sig)

        bucket_id = get_bucket_for_key(pub_key)
        key_file_name = 'bucket%d' % bucket_id
        full_key_path = root_dir + '/bucket_keys/%s' % key_file_name
        if not os.path.isfile(full_key_path + '_public.pem'):
            return jsonify({'error': 'howd u get this key wtf'})

        vk = VerifyingKey.from_pem(open(full_key_path + '_public.pem').read())
        try:
            vk.verify(sig, pub_key)
            old_key = ledger.get(Ledger.public_key == pub_key)
            if old_key != None:
                ledger.remove(doc_ids=[old_key.doc_id])
            ledger.insert({
                'public_key': pub_key,
                'b64_signature': b64_sig,
                'timestamp': time.time()
            })
            return jsonify({'status': 'ok'})
        except:
            return jsonify({'error': 'bad signature'})
Exemplo n.º 14
0
    async def recognize(self, websocket, path):
        b_face_encodings = await websocket.recv()
        #print(b_face_encoding)
        face_encodings, h, signature = pickle.loads(
            b_face_encodings, encoding='bytes')  #.decode()

        # check signature
        #to_hash = bytearray(face_encodings)#array.array('B', encodings).tostring()
        #h = hashlib.sha256(to_hash).digest()
        vk = VerifyingKey.from_pem(open("newpubkey.pem").read())
        #try:
        #    vk.verify_digest(signature, h)
        #except:
        #    print("Some dirty business here. Could not verify signature")

        #face_encoding = struct.unpack('%sd' % 128, b_face_encoding)
        ids, known_faces = self.get_known_faces()
        names = []
        confidences = []
        node_ids = []
        for face_encoding in face_encodings:
            idx, confidence = FaceRec.match_face(face_encoding, known_faces)
            if idx is not None:
                node = sess.retrieve(node_id=int(ids[idx].decode('utf-8')))[0]
                node_ids.append(int(ids[idx].decode('utf-8')))
                names.append(node.get_name())
                confidences.append(confidence)
            else:
                names.append("stranger")
                confidences.append(1.0)
                node_ids.append(-1)
        await websocket.send(
            pickle.dumps((names, confidences, node_ids), protocol=2))
Exemplo n.º 15
0
    def verify_encryption_key_signature(
            self, encryption_key_signature, encryption_key, verifying_key):
        """
        Utils function to verify integrity of worker encryption key using
        worker verification key
        @params encryption_key_signature - Signature computed on hash
                                           of encryption key
        @params encryption_key - Public encryption key of the worker
        @params verifying_key - Public signing key or verification key
                                of the worker
        returns SignatureStatus.PASSED in case of successful verification
                SignatureStatus.FAILED in case of verification failure
        """

        _verification_key = VerifyingKey.from_pem(verifying_key)
        encrypt_key_sig_bytes = hex_to_byte_array(encryption_key_signature)
        encrypt_key_bytes = crypto_utility.string_to_byte_array(encryption_key)
        encryption_key_hash = crypto_utility.compute_message_hash(
            encrypt_key_bytes)
        sig_result = _verification_key.verify_digest(
            bytes(encrypt_key_sig_bytes),
            bytes(encryption_key_hash),
            sigdecode=sigdecode_der)
        if sig_result:
            return SignatureStatus.PASSED
        return SignatureStatus.FAILED
Exemplo n.º 16
0
def verify_sign(pubkey, message, signature):
    """
        验证签名
    """
    verifier = VerifyingKey.from_pem(pubkey)
    h = sha256(message.encode('utf8'))
    return verifier.verify(binascii.unhexlify(signature), h.digest())
Exemplo n.º 17
0
def get_key():
    # 파일로부터 읽어들인 공개키, 개인키 리턴
    pri_key = SigningKey.from_pem(
        open(KEY_PATH + "/private.pem", encoding='utf-8').read())
    pub_key = VerifyingKey.from_pem(
        open(KEY_PATH + "/public.pem", encoding='utf-8').read())

    return pri_key, pub_key
Exemplo n.º 18
0
 def load_public_key(self):
     # Check settings validity
     if self.private_key:
         private_key = self.load_private_key()
         return private_key.get_verifying_key()
     elif self.public_key:
         with open(self.public_key, 'rb') as key_file:
             return VerifyingKey.from_pem(key_file.read())
Exemplo n.º 19
0
 def load_public_key(self):
     # Check settings validity
     if self.private_key:
         private_key = self.load_private_key()
         return private_key.get_verifying_key()
     elif self.public_key:
         with open(self.public_key, 'rb') as key_file:
             return VerifyingKey.from_pem(key_file.read())
Exemplo n.º 20
0
 async def whois(ctx, message):
     keyjson = json.load(open("keys.json"))
     for key in keyjson:
         public_key = VerifyingKey.from_pem(keyjson[key]["public"])
         out = str(base64.b64encode(public_key.to_string()), "utf-8")
         if ctx.args.public in out:
             user = message.channel.guild.get_member(int(key))
             await message.channel.send(user.display_name)
Exemplo n.º 21
0
 def verify_sign(self, pubkey,message,signature):
     """
     验证数字签名
     :return:
     """
     verifier = VerifyingKey.from_pem(pubkey)
     h = sha256(str(message).encode('utf-8'))
     return verifier.verify(binascii.unhexlify(signature), h.digest())
Exemplo n.º 22
0
def verify_sign(public_key, signature, message):
    vk = VerifyingKey.from_pem(b64decode(public_key.encode('utf-8')))
    try:
        result = vk.verify(b64decode(signature.encode('utf-8')),
                           message.encode('utf-8'))
        return result
    except:
        return False
Exemplo n.º 23
0
 def loadKeys(self):
     public_key = {}
     private_key = {}
     try:
         public_key = VerifyingKey.from_pem(open("public.pem").read())
         private_key = SigningKey.from_pem(open("private.pem").read())
         return public_key, private_key
     except:
         return self.generateKeys()
Exemplo n.º 24
0
def can_bypass(chal, sol):
    from ecdsa import VerifyingKey
    from ecdsa.util import sigdecode_der
    if not sol.startswith('b.'):
        return False
    sig = bytes.fromhex(sol[2:])
    with open("/kctf/pow-bypass/pow-bypass-key-pub.pem", "r") as fd:
        vk = VerifyingKey.from_pem(fd.read())
    return vk.verify(signature=sig, data=bytes(chal, 'ascii'), hashfunc=hashlib.sha256, sigdecode=sigdecode_der)
Exemplo n.º 25
0
def verify_signature(app_id, device_id, signature, publickey):
    """
      验证签名 服务端实现
    """
    public_key = VerifyingKey.from_pem(open(publickey).read())
    check_res = public_key.verify(base64.urlsafe_b64decode(signature),
                                  device_id,
                                  hashfunc=hashlib.sha256,
                                  sigdecode=sigdecode_der)
    return check_res
Exemplo n.º 26
0
def get_hashes(public_key_files):
    hashes = list()
    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
Exemplo n.º 27
0
def verify_signature(public_key, message, signature):
    message = message.encode()
    public_key = public_key.encode()
    print('public key :', public_key)
    public_key = VerifyingKey.from_pem(public_key)
    try:
        public_key.verify(signature, message)
        return True
    except BadSignatureError:
        return False
Exemplo n.º 28
0
def verify_sig():
    vk = VerifyingKey.from_pem(open("pub_key.pem").read())
    message = open("message_file1", "rb").read()
    sig = open("signature", "rb").read()
    print sig
    try:
        vk.verify(sig, message)
        print "GOOD SIGNATURE"
    except BadSignatureError:
        print "BAD SIGNATURE"
Exemplo n.º 29
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)
Exemplo n.º 30
0
def get_hashes(public_key_files):
    hashes = list()
    for fn in public_key_files:
        with open(fn, 'rb') as f:
            hashes.append(sha256(VerifyingKey.from_pem(f.read()).to_string()).digest()[:16])

    if len(hashes) != len(set(hashes)):
        raise RuntimeError("Duplicate public key found. Note that the public key corresponding to the private"
                           "key used for signing is automatically added, and must not be added explicitly.")

    return hashes
Exemplo n.º 31
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)
Exemplo n.º 32
0
def verify_file(args):
    from ecdsa import VerifyingKey

    public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
    signature = args.signature.read()
    message = args.file.read()

    if verify_signature(public_key, message, signature):
        print "Verification OK"
    else:
        print "Verification Failure"
Exemplo n.º 33
0
def verify_sign(pubkey, message, signature):
    """
    验证签名
    :param pubkey:公钥
    :param message:内容
    :param signature:签名
    :return:
    """
    verifier = VerifyingKey.from_pem(pubkey)
    h = sha256(str(message).encode('utf-8'))
    return verifier.verify(binascii.unhexlify(signature), h.digest())
Exemplo n.º 34
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)
Exemplo n.º 35
0
 def verify_signature(self, data):
     data = str.encode(data)
     with open(self.publickeyfile) as f:
         vk = VerifyingKey.from_pem(f.read())
         f.close()
     with open(self.signaturefilename, "rb") as f:
         signature = f.read()
         f.close()
     return vk.verify(signature,
                      data,
                      hashlib.sha256,
                      sigdecode=sigdecode_der)
Exemplo n.º 36
0
def receive_message(args):
    '''
    '''
    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
    from ecdsa import VerifyingKey

    backend = default_backend()
    key_size = 2048

    key_enc = args.message.read(key_size/8)
    iv = args.message.read(16)
    encrypted = args.message.read()

    private_key = serialization.load_pem_private_key(
        args.privateKey.read(),
        password=None,
        backend=backend
    )

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

    plain = decrypt(key, iv, encrypted)

    signature = plain[len(plain)-64:]
    plain = plain[:len(plain)-64]

    name, extension = os.path.splitext(args.message.name)

    name = os.path.basename(name)

    with open(name, 'wb') as plain_file:
        plain_file.write(plain)

    with open('%s.sig' % name, 'wb') as sig_file:
        sig_file.write(signature)

    public_key = VerifyingKey.from_pem(args.verificaitonKey.read())
    if verify_signature(public_key, plain, signature):
        print "Verification OK"
    else:
        print "Verification Failure"
def recover():
	txt1 = "Students reported that students post to discussion forums more frequently and are irrevocable provided the stated conditions are met."
	sig1 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccdcd7a46d769ee43467a01453214868094ca228cb5eebc953a39fb9bbaf865f4dbe1dad9b5f9f1bed75671e0db5433f0ed'''.strip().decode('hex')

	txt2 = "But is this enough? And what new threats could be using it as a friend or fan.[2]"
	sig2 = '''a0289c0fa7e87f1ab1e94b577f43691ebd70c04b0e62ca7eaaf1791983d512e7bbc843ee3a2a0430455e9f755f832ccd54d4f8306fe11bd4a28a491ddf596c64cd98c93d7fa9a05acead17e42e96ed1a190a2fddd7c695b8d9bce43f221b4e1b'''.strip().decode('hex')

	public_key_ec = VerifyingKey.from_pem(public_key_ec_pem)
	print "Verify1: " + str(public_key_ec.verify(sig1, txt1))
	print "Verify2: " + str(public_key_ec.verify(sig2, txt2))
	print "curve order:", public_key_ec.curve.order

	key = recover_key(txt1, sig1, txt2, sig2, public_key_ec)
	print key
Exemplo n.º 38
0
    def put(self, ndef_message):
        print "client has put an NDEF message"
        #print ndef_message.pretty()
        keyRecord = ndef_message.pop()
        sigRecord = ndef_message.pop()
        actionRecord = ndef_message.pop()

        vk = VerifyingKey.from_pem(keyRecord.data.decode("utf-8"))
        print vk.to_pem() == keyRecord.data.decode("utf-8")
        
        print "Key created. Yay!"
        try:
            tmp = vk.verify(sigRecord.data, "test", hashfunc=hashlib.sha256())
            print tmp
        except Exception, e:
            print "Signature Error"
Exemplo n.º 39
0
def is_jose_sig_valid(b64_jpayload, jose_sig, vk_pem):
    jpayload = b64url_dec(b64_jpayload, MalformedSignatureError)

    b64_jheader = dget(jose_sig, 'protected', MalformedSignatureError)
    jheader = b64url_dec(b64_jheader, MalformedSignatureError)

    b64_sig = dget(jose_sig, 'signature', MalformedSignatureError)
    sig_der = b64url_dec(b64_sig, MalformedSignatureError)

    vk = VerifyingKey.from_pem(vk_pem)
    vk_order = vk.curve.order
    b64_sig_string = base64url_encode(sig_der_to_string(sig_der, vk_order))

    try:
        jws.verify(jheader, jpayload, b64_sig_string, vk, is_json=True)
        return True
    except jws.SignatureError:
        return False
Exemplo n.º 40
0
def is_jws_sig_valid(b64_jws_sig, vk_pem):
    parts = b64_jws_sig.split('.')
    if len(parts) != 3:
        raise MalformedSignatureError

    # Extract parts to verify signature
    jheader_b64, jbody_b64, sig_der_b64 = parts
    jheader = b64url_dec(jheader_b64)
    jbody = b64url_dec(jbody_b64)
    sig_der = b64url_dec(sig_der_b64)

    vk = VerifyingKey.from_pem(vk_pem)
    vk_order = vk.curve.order
    sig_string_b64 = base64url_encode(sig_der_to_string(sig_der, vk_order))

    try:
        jws.verify(jheader, jbody, sig_string_b64, vk, is_json=True)
        return True
    except jws.SignatureError:
        return False
Exemplo n.º 41
0
def verify_sth(sth_json,sigkey):
    # Signature is calculated over this structure
    # digitally-signed struct {
    #       Version version;
    #       SignatureType signature_type = tree_hash;
    #       uint64 timestamp;
    #       uint64 tree_size;
    #       opaque sha256_root_hash[32];
    #   } TreeHeadSignature;
    treehash = struct.pack(">B",1)
    version = struct.pack(">B",0)
    # put the decimal encoded values into byte buffers
    tstampbuf = struct.pack(">Q",sth_json["timestamp"])
    tsizebuf = struct.pack(">Q",sth_json["tree_size"])
    # convert base64 root hash to binary
    srhbuf = base64.b64decode(sth_json["sha256_root_hash"])
    buf = version + treehash + tstampbuf + tsizebuf + srhbuf

    # Per RFC 6962, either support RSA or ECDSA with NIST256p curves
    # determine this by deserializing TLS signature structure

    print base64.b64encode(buf)
    # Get SHA256 digest of buffer
    m = SHA256.new(buf)
    # convert base64 signature in message to binary
    sigbuf = base64.b64decode(sth_json["tree_head_signature"])
    b = io.BytesIO(sigbuf)
    hashalgo ,= struct.unpack(">b",b.read(1))
    sigalgo ,= struct.unpack(">b",b.read(1))
    # Signature is opaque data structure per RFC 5246. Length of the signature
    # is stored in first n bytes where n is number of bytes sufficient to hold max size
    # of signature
    # Defined as 
    # struct {
    #     SignatureAndHashAlgorithm algorithm;
    #     opaque signature<0..2^16-1>;
    #  } DigitallySigned;
    # 2 bytes needed to specify 2^16 - 1

    siglen ,= struct.unpack(">h",b.read(2))
    buf2 = b.read()
    if siglen != len(buf2):
	print 'Signature invalid; signature wrong length'
	return False


    # Verify the signature
    print sigkey
    # From RFC 5246 section 7.4.1.4.1 
    # enum {
    #      none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
    #      sha512(6), (255)
    #  } HashAlgorithm;

    #  enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
    #    SignatureAlgorithm;

    if hashalgo == 4 and sigalgo == 3:
	vk = VerifyingKey.from_pem(sigkey)
	try:
	    vk.verify(buf2,buf,hashfunc=hashlib.sha256,
	    sigdecode=ecdsa.util.sigdecode_der)
	    print "The signature is authentic."
	except BadSignatureError:
		print "The signature is not authentic."
		return False
    else:
	print "Unsupported signature/hash algorithm"
	return False

    return True
        Get the user's verification key
        Returns:
            Verification key from meta-container (Keys) in meta-tenant
        """
        auth = v3.Password(auth_url=AUTH_URL,username=ADMIN_USER,password=ADMIN_KEY,project_name='demo',project_domain_id="Default",user_domain_name="Default")
        sess = session.Session(auth=auth)
        barbican = bc.Client(session=sess)
        keystone = kc.Client(session=sess)
        try:
            user = keystone.users.get(usrID)
            dict_keys = json.loads(user.description)
            ref = dict_keys.get('Verification_Key','')
            ref = "%s/secrets/%s" %(BARBICAN_URL,ref)
            secret_node = barbican.secrets.get(ref)
        except Exception,err:
            return
        a = VerifyingKey.from_pem(secret_node.payload)
        return a

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)
Exemplo n.º 43
0
from ecdsa import VerifyingKey
from ecdsa.numbertheory import inverse_mod

#sources:
#http://antonio-bc.blogspot.com/2013/12/mathconsole-ictf-2013-writeup.html
#https://neg9.org/news/2015/8/12/openctf-2015-veritable-buzz-1-crypto-300-writeup

#public key we pulled from the server
public_key_ec_pem = """
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEgTxPtDMGS8oOT3h6fLvYyUGq/BWeKiCB
sQPyD0+2vybIT/Xdl6hOqQd74zr4U2dkj+2q6+vwQ4DCB1X7HsFZ5JczfkO7HCdY
I7sGDvd9eUias/xPdSIL3gMbs26b0Ww0
-----END PUBLIC KEY-----
"""
public_key_ec = VerifyingKey.from_pem(public_key_ec_pem.strip())
curve_order = public_key_ec.curve.order

#"help" and "time" sigs we obtained from the packet capture
h = "c0e1fc4e3858ac6334cc8798fdec40790d7ad361ffc691c26f2902c41f2b7c2fd1ca916de687858953a6405423fe156cfd7287caf75247c9a32e52ab8260e7ff1e46e55594aea88731bee163035f9ee31f2c2965ac7b2cdfca6100d10ba23826"
t = "c0e1fc4e3858ac6334cc8798fdec40790d7ad361ffc691c26f2902c41f2b7c2fd1ca916de687858953a6405423fe156c0cbebcec222f83dc9dd5b0d4d8e698a08ddecb79e6c3b35fc2caaa4543d58a45603639647364983301565728b504015d"


def string_to_number(tstr):
    return int(binascii.hexlify(tstr), 16)
    
def sha256(content):
    sha256_hash = hashlib.sha256()
    sha256_hash.update(content)
    return sha256_hash.digest()
import datetime
from binascii import unhexlify
from ecdsa import VerifyingKey
import hashlib
import signal

PORT = 6002

PUBLIC_KEY = """
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEgTxPtDMGS8oOT3h6fLvYyUGq/BWeKiCB
sQPyD0+2vybIT/Xdl6hOqQd74zr4U2dkj+2q6+vwQ4DCB1X7HsFZ5JczfkO7HCdY
I7sGDvd9eUias/xPdSIL3gMbs26b0Ww0
-----END PUBLIC KEY-----
"""
vk = VerifyingKey.from_pem(PUBLIC_KEY.strip())

print(vk.to_string())

help_string = b"""
COMMANDS:
* read [file]
 - prints contents of file
* time
 - prints the current time
* help
 - prints this message
"""

class RequestHandler(ss.StreamRequestHandler):
    def run_command(self, msg):