예제 #1
0
    def get_gcm_decoded_private_key(encrypted_key_str: str, password: str, b58_address: str, salt: str, n: int,
                                    scheme: SignatureScheme) -> str:
        """
        This interface is used to decrypt an private key which has been encrypted.

        :param encrypted_key_str: an gcm encrypted private key in the form of string.
        :param password: the secret pass phrase to generate the keys from.
        :param b58_address: a base58 encode address which should be correspond with the private key.
        :param salt: a string to use for better protection from dictionary attacks.
        :param n: CPU/memory cost parameter.
        :param scheme: the signature scheme.
        :return: a private key in the form of string.
        """
        r = 8
        p = 8
        dk_len = 64
        scrypt = Scrypt(n, r, p, dk_len)
        derived_key = scrypt.generate_kd(password, salt)
        iv = derived_key[0:12]
        key = derived_key[32:64]
        encrypted_key = base64.b64decode(encrypted_key_str).hex()
        mac_tag = bytes.fromhex(encrypted_key[64:96])
        cipher_text = bytes.fromhex(encrypted_key[0:64])
        private_key = AESHandler.aes_gcm_decrypt_with_iv(cipher_text, b58_address.encode(), mac_tag, key, iv)
        if len(private_key) == 0:
            raise SDKException(ErrorCode.decrypt_encrypted_private_key_error)
        acct = Account(private_key, scheme)
        if acct.get_address().b58encode() != b58_address:
            raise SDKException(ErrorCode.other_error('Address error.'))
        return private_key.hex()
예제 #2
0
 def test_generate_kd(self):
     scrypt = Scrypt()
     salt = ''.join(map(chr, bytes([0xfa, 0xa4, 0x88, 0x3d])))
     kd = scrypt.generate_kd('passwordtest', salt)
     target_kd = '9f0632e05eab137baae6e0a83300341531e8638612a08042d3a4074578869af1' \
                 'ccf5008e434d2cae9477f9e6e4c0571ab65a60e32e8c8fc356d95f64dd9717c9'
     target_kd = bytes.fromhex(target_kd)
     self.assertEqual(target_kd, kd)
예제 #3
0
    def export_gcm_encrypted_private_key(self, password: str, salt: str, n: int = 16384) -> str:
        """
        This interface is used to export an AES algorithm encrypted private key with the mode of GCM.

        :param password: the secret pass phrase to generate the keys from.
        :param salt: A string to use for better protection from dictionary attacks.
                      This value does not need to be kept secret, but it should be randomly chosen for each derivation.
                      It is recommended to be at least 8 bytes long.
        :param n: CPU/memory cost parameter. It must be a power of 2 and less than 2**32
        :return: an gcm encrypted private key in the form of string.
        """
        r = 8
        p = 8
        dk_len = 64
        scrypt = Scrypt(n, r, p, dk_len)
        derived_key = scrypt.generate_kd(password, salt)
        iv = derived_key[0:12]
        key = derived_key[32:64]
        hdr = self.__address.b58encode().encode()
        mac_tag, cipher_text = AESHandler.aes_gcm_encrypt_with_iv(self.__private_key, hdr, key, iv)
        encrypted_key = bytes.hex(cipher_text) + bytes.hex(mac_tag)
        encrypted_key_str = base64.b64encode(bytes.fromhex(encrypted_key))
        return encrypted_key_str.decode('utf-8')
예제 #4
0
    def import_identity(self, label: str, encrypted_pri_key: str, pwd: str, salt: str, b58_address: str) -> Identity:
        """
        This interface is used to import identity by providing encrypted private key, password, salt and
        base58 encode address which should be correspond to the encrypted private key provided.

        :param label: a label for identity.
        :param encrypted_pri_key: an encrypted private key in base64 encoding from.
        :param pwd: a password which is used to encrypt and decrypt the private key.
        :param salt: a salt value which will be used in the process of encrypt private key.
        :param b58_address: a base58 encode address which correspond with the encrypted private key provided.
        :return: if succeed, an Identity object will be returned.
        """
        scrypt_n = Scrypt().n
        pri_key = Account.get_gcm_decoded_private_key(encrypted_pri_key, pwd, b58_address, salt, scrypt_n, self.scheme)
        info = self.__create_identity(label, pwd, salt, pri_key)
        for identity in self.wallet_in_mem.identities:
            if identity.ont_id == info.ont_id:
                return identity
        raise SDKException(ErrorCode.other_error('Import identity failed.'))
예제 #5
0
 def load_file(self):
     with open(self.__wallet_path, 'rb') as f:
         content = f.read()
         if content.startswith(codecs.BOM_UTF8):
             content = content[len(codecs.BOM_UTF8):]
         content = content.decode('utf-8')
         wallet_dict = json.loads(content)
         create_time = wallet_dict.get('createTime', '')
         default_id = wallet_dict.get('defaultDID', '')
         default_address = wallet_dict.get('defaultAccountAddress', '')
         identities = wallet_dict.get('identities', list())
         try:
             scrypt_dict = wallet_dict['scrypt']
             scrypt_obj = Scrypt(scrypt_dict.get('n', 16384), scrypt_dict.get('r', 8), scrypt_dict.get('p', 8),
                                 scrypt_dict.get('dk_len', 64))
             wallet = WalletData(wallet_dict['name'], wallet_dict['version'], create_time, default_id,
                                 default_address, scrypt_obj, identities, wallet_dict['accounts'])
         except KeyError as e:
             raise SDKException(ErrorCode.param_err(f'wallet file format error: {e}.'))
     return wallet
예제 #6
0
 def __init__(self,
              name: str = 'MyWallet',
              version: str = '1.1',
              create_time: str = '',
              default_id: str = '',
              default_address='',
              scrypt: Scrypt = Scrypt(),
              identities: List[Identity] = None,
              accounts: List[AccountData] = None):
     if not isinstance(scrypt, Scrypt):
         raise SDKException(
             ErrorCode.other_error('Wallet Data init failed'))
     if identities is None:
         identities = list()
     if accounts is None:
         accounts = list()
     self.name = name
     self.version = version
     self.create_time = create_time
     self.default_ont_id = default_id
     self.default_account_address = default_address
     self.scrypt = scrypt
     self.identities = list()
     self.accounts = list()
     for dict_identity in identities:
         if isinstance(dict_identity, dict):
             list_controls = list()
             is_default = dict_identity.get('isDefault', False)
             for ctrl_data in dict_identity['controls']:
                 hash_value = ctrl_data.get('hash', 'sha256')
                 public_key = ctrl_data.get('publicKey', '')
                 try:
                     ctrl = Control(kid=ctrl_data['id'],
                                    address=ctrl_data['address'],
                                    enc_alg=ctrl_data['enc-alg'],
                                    key=ctrl_data['key'],
                                    algorithm=ctrl_data['algorithm'],
                                    salt=ctrl_data['salt'],
                                    param=ctrl_data['parameters'],
                                    hash_value=hash_value,
                                    public_key=public_key)
                 except KeyError:
                     raise SDKException(
                         ErrorCode.other_error('invalid parameters.'))
                 list_controls.append(ctrl)
             try:
                 identity = Identity(ont_id=dict_identity['did'],
                                     label=dict_identity['label'],
                                     lock=dict_identity['lock'],
                                     controls=list_controls,
                                     is_default=is_default)
             except KeyError:
                 raise SDKException(
                     ErrorCode.other_error('invalid parameters.'))
             self.identities.append(identity)
         else:
             self.identities = identities
             break
     for dict_account in accounts:
         if isinstance(dict_account, dict):
             try:
                 public_key = dict_account['publicKey']
             except KeyError:
                 public_key = ''
             try:
                 acct = AccountData(
                     b58_address=dict_account['address'],
                     enc_alg=dict_account['enc-alg'],
                     key=dict_account['key'],
                     algorithm=dict_account['algorithm'],
                     salt=dict_account['salt'],
                     param=dict_account['parameters'],
                     label=dict_account['label'],
                     public_key=public_key,
                     sig_scheme=dict_account['signatureScheme'],
                     is_default=dict_account['isDefault'],
                     lock=dict_account['lock'])
             except KeyError:
                 raise SDKException(ErrorCode.param_error)
             self.accounts.append(acct)
         else:
             self.accounts = accounts
             break
예제 #7
0
 def test_set_r(self):
     r = 5
     scrypt = Scrypt(r)
     scrypt.r = r
     self.assertEqual(r, scrypt.r)
예제 #8
0
 def test_set_p(self):
     n = 5
     scrypt = Scrypt()
     scrypt.n = n
     self.assertEqual(n, scrypt.n)
예제 #9
0
 def test_set_dk_len(self):
     dk_len = 64
     scrypt = Scrypt()
     scrypt.dk_len = dk_len
     self.assertEqual(dk_len, scrypt.dk_len)