Ejemplo n.º 1
0
def verify_credential(signed_credential, did):
    """
    Verify credential signed with RSA key of the DID
    @parma signed_credential as a dict
    @param did as a str
    return bool
    """
    read = requests.get('https://talao.co/resolver?did=' + did)
    for Key in read.json()['publicKey']:
        if Key.get('id') == did + "#secondary":
            public_key = Key['publicKeyPem']
            break
    jws = JsonWebSignature()
    try:
        jws.deserialize_compact(signed_credential['proof']['jws'], public_key)
    except:
        return False
    return True
Ejemplo n.º 2
0
def json_verify(msg: Union[bytes, dict, str],
                pubKey: Union[str, Dict[str, str]] = None) -> bool:
    msg: dict = msg if isinstance(msg, dict) else json.loads(msg)
    if signature := msg.pop("signature", None):
        sig = signature.split(".")
        header = json.loads(base64.b64decode(sig[0]))
        sig[1] = base64.b64encode(b'.'.join([
            base64.b64encode(canonicaljson.encode_canonical_json(header)),
            base64.b64encode(canonicaljson.encode_canonical_json(msg))
        ])).decode("utf-8").rstrip("=")

        jws = JsonWebSignature()
        key = Path(pubKey).read_bytes() if isinstance(
            pubKey, str) else partial(load_key, keys=pubKey)
        try:
            jws.deserialize_compact(".".join(sig), key)
            return True
        except errors.BadSignatureError:
            return False
Ejemplo n.º 3
0
def test_keys():
    """Try to store/get/remove keys"""
    # JWS
    jws = JsonWebSignature(algorithms=["RS256"])
    code_payload = {
        "user_id": "user",
        "scope": "scope",
        "client_id": "client",
        "redirect_uri": "redirect_uri",
        "code_challenge": "code_challenge",
    }

    # Token metadata
    header = {"alg": "RS256"}
    payload = {
        "sub": "user",
        "iss": "issuer",
        "scope": "scope",
        "setup": "setup",
        "group": "my_group"
    }

    # Remove all keys
    result = db.removeKeys()
    assert result["OK"], result["Message"]

    # Check active keys
    result = db.getActiveKeys()
    assert result["OK"], result["Message"]
    assert result["Value"] == []

    # Create new one
    result = db.getPrivateKey()
    assert result["OK"], result["Message"]

    private_key = result["Value"]
    assert isinstance(private_key, RSAKey)

    # Sign token
    header["kid"] = private_key.thumbprint()

    # Find key by KID
    result = db.getPrivateKey(header["kid"])
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert result["Value"].as_dict(True) == private_key.as_dict(True)

    # Sign token
    token = jwt.encode(header, payload, private_key)
    # Sign auth code
    code = jws.serialize_compact(header, json_b64encode(code_payload),
                                 private_key)

    # Get public key set
    result = db.getKeySet()
    keyset = result["Value"]
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert bool([
        key for key in keyset.as_dict(True)["keys"]
        if key["kid"] == header["kid"]
    ])

    # Read token
    _payload = jwt.decode(token, JsonWebKey.import_key_set(keyset.as_dict()))
    assert _payload == payload
    # Read auth code
    data = jws.deserialize_compact(code, keyset.keys[0])
    _code_payload = json_loads(urlsafe_b64decode(data["payload"]))
    assert _code_payload == code_payload
Ejemplo n.º 4
0
 def validate_jwt_token(self, token):
     jws = JsonWebSignature(algorithms=JWS_ALGORITHMS)
     secret = bytes(self.app.config['SECRET_KEY'], 'utf-8')
     data = jws.deserialize_compact(token, secret)
     return json.loads(data['payload'])