Example #1
0
def notify_withdraw_to_outer_project( callback_url : str, req_data : dict,
                                      logger, svr_sign_key : str )-> NotifyFuncResponse:
    """
    提币回调通知统一接口
    :param serial_id:
    :return:
    """
    api_name = 'notifywithdraw'
    timestamp_str = str(int(time.time() * 1000))
    data_json_str = json.dumps(req_data, separators=(',', ':'), sort_keys=True)  # 按照key字母顺序排序
    join_str = '|'.join([timestamp_str, api_name, data_json_str])
    sign_msg_bytes = join_str.encode('utf8')
    sk = SigningKey(sk_s=svr_sign_key.encode('utf8'), prefix='', encoding='hex')
    signature_bytes = sk.sign(msg=sign_msg_bytes, prefix='', encoding='hex')
    signature_str = signature_bytes.decode('utf8')
    # print('json_str:{}'.format(data_json_str))

    req_headers = {
        'User-Agent' : 'shbao/1.0',  #自定义User-Agent
        'PG_NOTIFY_TIMESTAMP': timestamp_str,
        'PG_NOTIFY_SIGNATURE': signature_str
    }

    ret_info = NotifyFuncResponse()
    ret_info.is_notify_successed = False

    try:
        send_notify_rst = requests.post(url=callback_url, json=req_data, headers=req_headers, timeout=5)
        logger.info(send_notify_rst)

        http_status_code = send_notify_rst.status_code
        if http_status_code == 204 or http_status_code == 200:
            ret_info.is_notify_successed = True
    except Exception as e:
        logger.error('{}'.format(e))
        ret_info.is_notify_successed = False


    return ret_info
Example #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
Example #3
0
 def sign(self, privKey: ed25519.SigningKey) -> None:
     self.signature = privKey.sign(b"MEROS" + self.hash)
Example #4
0
 def sign(self, priv: ed25519.SigningKey):
     self.pubkey = priv.get_verifying_key()
     self.signature = priv.sign(self.hash())
Example #5
0
 def sign_bytes(bytes_to_sign: bytes,
                private_key: ed25519.SigningKey) -> bytes:
     sig = private_key.sign(bytes_to_sign)
     return sig
def sign_msg(sign_key: str, msg: bytes) -> any:
    sk = SigningKey(sk_s=sign_key.encode('latin1'), prefix='', encoding='hex')
    sig = sk.sign(msg=msg, prefix='', encoding='hex')
    return sig
Example #7
0
#! /usr/bin/env python3
import binascii
import sys
import hashlib

from ed25519 import SigningKey

if len(sys.argv) == 1:
    print("usage: fw_sign <firmware.bin> <privatekey.bin>")
    sys.exit(0)

with open(sys.argv[2], "rb") as privk:
    sk = SigningKey(privk.read(64))
    with open(sys.argv[1], "rb") as fw:
        sha512 = hashlib.sha512()
        while True:
            data = fw.read(2048)
            if not data: break
            sha512.update(data)

        digest = sha512.digest()
        print("sha512   : "+bytes.decode(binascii.hexlify(digest)))
        signed_firmware = sk.sign(sha512.digest())
        print("signature: "+bytes.decode(binascii.hexlify(signed_firmware)))
        with open(sys.argv[1]+".sig", "w+b") as fw_s:
            fw_s.write(signed_firmware)
    except Exception as e:
        ERRORS += 1
        nagios(UBIRCH_CLIENT, UBIRCH_ENV, service + "-deepCheck", NAGIOS_ERROR,
               str(e))

# check, register and deregister key
try:
    if api.is_identity_registered(uuid):
        # remove any existing key
        r = api.deregister_identity(
            str.encode(
                json.dumps({
                    "publicKey":
                    bytes.decode(base64.b64encode(vk.to_bytes())),
                    "signature":
                    bytes.decode(base64.b64encode(sk.sign(vk.to_bytes())))
                })))
        if r.status_code != 200:
            nagios(UBIRCH_CLIENT, UBIRCH_ENV, KEY_SERVICE + "-deregister",
                   NAGIOS_ERROR, "{} {}".format(r.status_code,
                                                bytes.decode(r.content)))
except Exception as e:
    nagios(UBIRCH_CLIENT, UBIRCH_ENV, KEY_SERVICE + "-deregister",
           NAGIOS_ERROR, "{}".format(str(e)))

if api.is_identity_registered(uuid):
    nagios(UBIRCH_CLIENT, UBIRCH_ENV, KEY_SERVICE + "-register", NAGIOS_ERROR,
           "{}".format("public key already registered"))
    exit(-1)

# register key
Example #9
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
Example #10
0
def sign(msg: bytes, priv: str) -> bytes:
    skByte = bytes.fromhex(priv)
    skSigning = SigningKey(skByte)

    return skSigning.sign(msg)