Esempio n. 1
0
def verify_sig(verify_key: str, sig: str, msg: bytes) -> bool:
    vk = VerifyingKey(vk_s=verify_key, prefix='', encoding='hex')
    try:
        vk.verify(sig=sig, msg=msg, prefix='', encoding='hex')
    except Exception as e:
        return False
    return True
Esempio n. 2
0
class EdDSA(KeyDto, IRemmeKeys):
    """
    EdDSA (ed25519) class implementation.

    References::
        - https://github.com/warner/python-ed25519
    """

    def __init__(self, private_key, public_key):
        """
        Constructor for EdDSA key pair.
        If only private key available then public key will be generate from private.

        Args:
            private_key (bytes): ed25519 private key
            public_key (bytes, optional): ed25519 public key
        """
        super(EdDSA, self).__init__()

        if private_key and public_key:
            self._private_key = private_key
            self._public_key = public_key
            self._private_key_obj = SigningKey(self._private_key)
            self._public_key_obj = VerifyingKey(self._public_key)

        elif private_key:
            self._private_key = private_key
            self._private_key_obj = SigningKey(self._private_key)

            self._public_key_obj = self._private_key_obj.get_verifying_key()
            self._public_key = self._public_key_obj.to_bytes()

        elif public_key:
            self._public_key = public_key
            self._public_key_obj = VerifyingKey(self._public_key)

        if self._private_key:
            self._private_key_hex = self._private_key.hex()

        self._public_key_hex = self._public_key.hex()

        self._address = generate_address(
            _family_name=RemmeFamilyName.PUBLIC_KEY.value,
            _public_key_to=self._public_key,
        )
        self._key_type = KeyType.EdDSA

    @staticmethod
    def generate_key_pair(seed=None):
        """
        Generate public and private key pair.

        Args:
            seed (bytes, optional): seed

        Returns:
            Generated key pair in bytes.
        """
        if seed:
            private_key_obj, public_key_obj = ed25519.SigningKey(seed), ed25519.VerifyingKey(seed)
            return private_key_obj.to_bytes(), public_key_obj.to_bytes()

        private_key_obj, public_key_obj = ed25519.create_keypair(entropy=os.urandom)
        return private_key_obj.to_bytes(), public_key_obj.to_bytes()

    @staticmethod
    def get_address_from_public_key(public_key):
        """
        Get address from public key.
        Args:
            public_key (bytes): public key in bytes

        Returns:
            Address in blockchain generated from public key string.
        """
        return generate_address(RemmeFamilyName.PUBLIC_KEY.value, public_key)

    def sign(self, data, rsa_signature_padding=None):
        """
        Sign provided data with selected key implementation.

        Args:
            data (str): data string which will be signed
            rsa_signature_padding (RsaSignaturePadding, optional): not used in EdDSA

        Returns:
            Hex string of signature.
        """
        if self._private_key_obj is None:
            raise Exception('Private key is not provided!')

        if isinstance(data, str):
            data = utf8_to_bytes(data)

        return self._private_key_obj.sign(msg=hashlib.sha256(data).digest())

    def verify(self, data, signature, rsa_signature_padding=None):
        """
        Verify signature for selected key implementation.

        Args:
            data (str): data string which will be verified
            signature (str): hex string of signature
            rsa_signature_padding (RsaSignaturePadding, optional): not used in EdDSA

        Returns:
            Boolean ``True`` if signature is correct, or ``False`` if invalid.
        """
        if isinstance(data, str):
            data = utf8_to_bytes(data)

        try:
            self._public_key_obj.verify(
                sig=signature,
                msg=hashlib.sha256(data).digest(),
            )
            return True

        except ed25519.BadSignatureError:
            return False
Esempio n. 3
0
dongle = getDongle(True)
publicKey = dongle.exchange(bytes("8004000000".decode('hex')))
print "publicKey " + str(publicKey).encode('hex')
try:
    offset = 0
    while offset <> len(textToSign):
        if (len(textToSign) - offset) > 255:
            chunk = textToSign[offset:offset + 255]
        else:
            chunk = textToSign[offset:]
        if (offset + len(chunk)) == len(textToSign):
            p1 = 0x80
        else:
            p1 = 0x00
        apdu = bytes("8002".decode('hex')) + chr(p1) + chr(0x00) + chr(
            len(chunk)) + bytes(chunk)
        signature = dongle.exchange(apdu)
        offset += len(chunk)
    print "signature " + str(signature).encode('hex')
    vk = VerifyingKey(bytes(publicKey))
    vk.verify(bytes(signature), textToSign)
    print "verified True"
except BadSignatureError:
    print "verified False"
except CommException as comm:
    if comm.sw == 0x6985:
        print "Aborted by user"
    else:
        print "Invalid status " + comm.sw
Esempio n. 4
0
def main():
    pg_api_key = 'ad68accaab14a18e15afe21f1330acac5ee3bb4d0c2709443b7d4def89b985bc'
    pg_client_sign_key = '7d9c911ca987e85c90af66511f0ba31ea95996ba7a095b5afcf58df82ae0016c'
    pg_client_verify_key = '77dbfd30dedf746fb6088017cf5fdcbe59411686784bd5a27ca40cef26cab4f7'
    api_url = "http://127.0.0.1:59001/api/demo/this_is_api_name"
    api_name = 'this_is_api_name'

    data = {
        'book':'book name',
        'apple': 'apple name',
        'cat': 'cat name',
        'null_field': None,
        'list_field': ['bbbbb','ccccc','aaaaaa'],
        'object_field':{
            'ccc': '0000',
            'bb': '11111',
            'aaa': '22222'
        },
        'is_ok': True,
    }

    data_json_str = json.dumps(data, separators=(',', ':'), sort_keys=True)  # 按照key字母顺序排序
    print('json_str:{}'.format(data_json_str))

    print('------------------------------\n\n')

    # timestamp_str = str(int(time.time() * 1000))
    timestamp_str = '1590156401029'
    print('tmpstamp_str:{}'.format(timestamp_str))

    print('------------------------------\n\n')
    join_str = '|'.join([timestamp_str, api_name, data_json_str])
    print('join_str:{}'.format(join_str))

    print('------------------------------\n\n')
    sign_msg_bytes = join_str.encode('utf8')
    print('sign_msg_bytes:{}'.format(sign_msg_bytes))

    print('------------------------------\n\n')

    sk = SigningKey(sk_s=pg_client_sign_key.encode('utf8'), prefix='', encoding='hex')
    signature_bytes = sk.sign(msg=sign_msg_bytes, prefix='', encoding='hex')
    print('signature_bytes:{}'.format(signature_bytes))
    print('------------------------------\n\n')

    signature_str = signature_bytes.decode('utf8')
    print('signature_str:{}'.format(signature_str))
    print('------------------------------\n\n')

    req_headers = {
        'ContentType': 'application/json',
        'PG_API_KEY': pg_api_key,
        'PG_API_TIMESTAMP': timestamp_str,
        'PG_API_SIGNATURE': signature_str
    }

    #请求接口
    # rsp = requests.post(url=api_url, json=data, headers=req_headers)

    try:
        vk = VerifyingKey(vk_s=pg_client_verify_key, prefix='', encoding='hex')
        vk.verify(sig=signature_str, msg=sign_msg_bytes, prefix='', encoding='hex')
        print('验签成功')
    except Exception as e:
        print('验签失败')

    pass