def test_OOP(self):
        sk_s = unhexlify("4ba96b0b5303328c7405220598a587c4"
                         "acb06ed9a9601d149f85400195f1ec3d"
                         "a66d161e090652b054740748f059f92a"
                         "5b731f1c27b05571f6d942e4f8b7b264")
        sk = ed25519.SigningKey(sk_s)
        self.failUnlessEqual(len(sk.to_bytes()), 64)
        self.failUnlessEqual(sk.to_bytes(), sk_s)

        sk2_seed = unhexlify("4ba96b0b5303328c7405220598a587c4"
                             "acb06ed9a9601d149f85400195f1ec3d")
        sk2 = ed25519.SigningKey(sk2_seed)
        self.failUnlessEqual(sk2.to_bytes(), sk.to_bytes())

        vk = sk.get_verifying_key()
        self.failUnlessEqual(len(vk.to_bytes()), 32)
        exp_vks = unhexlify("a66d161e090652b054740748f059f92a"
                            "5b731f1c27b05571f6d942e4f8b7b264")
        self.failUnlessEqual(vk.to_bytes(), exp_vks)
        self.failUnlessEqual(ed25519.VerifyingKey(vk.to_bytes()), vk)
        msg = b"hello world"
        sig = sk.sign(msg)
        self.failUnlessEqual(len(sig), 64)
        exp_sig = unhexlify("6eaffe94f2972b35158b6aaa9b69c1da"
                            "97f0896aca29c41b1dd7b32e6c9e2ff6"
                            "76fc8d8b034709cdcc37d8aeb86bebfb"
                            "173ace3c319e211ea1d7e8d8884c1808")
        self.failUnlessEqual(sig, exp_sig)
        self.failUnlessEqual(vk.verify(sig, msg), None)  # also, don't throw
        self.failUnlessRaises(ed25519.BadSignatureError, vk.verify, sig,
                              msg + b".. NOT!")
Exemple #2
0
def main():
    if len(sys.argv) < 3:
        usage()
        return

    if sys.argv[1] == "vk":
        # Generate verify key
        with open(sys.argv[2], "rb") as f:
            secret = f.read()
        if len(secret) != 32:
            print("ERROR: Secret must be 32 bytes!")
            return

        sk = ed25519.SigningKey(secret)
        vk = sk.get_verifying_key()
        print(vk.to_ascii(encoding='base64').decode('ascii'))

    elif sys.argv[1] == "sign":
        # Sign a command
        with open(sys.argv[2], "rb") as f:
            secret = f.read()
        if len(secret) != 32:
            print("ERROR: Secret must be 32 bytes!")
            return

        sk = ed25519.SigningKey(secret)

        is_special = sys.argv[4] == "!!"
        bytes_to_sign = b'\x00' if not is_special else b'\x01'

        # Nonce
        nonce = binascii.unhexlify(sys.argv[3])
        bytes_to_sign += nonce

        bytes_to_sign += sys.argv[5].encode('utf-8')
        sig = sk.sign(bytes_to_sign, encoding='base64').decode('ascii')
        print(sig)

    elif sys.argv[1] == "verify":
        # Verify a command
        vk = ed25519.VerifyingKey(sys.argv[2], encoding='base64')

        is_special = sys.argv[5] == "!!"
        bytes_to_sign = b'\x00' if not is_special else b'\x01'

        # Nonce
        nonce = binascii.unhexlify(sys.argv[4])
        bytes_to_sign += nonce

        bytes_to_sign += sys.argv[6].encode('utf-8')

        try:
            vk.verify(sys.argv[3], bytes_to_sign, encoding='base64')
            print("Signature OK!")
        except ed25519.BadSignatureError:
            print("Signature invalid!")

    else:
        usage()
    def setup(self):
        super().setup()

        if self.cnf.newprivatekey:
            if self.cnf.privatekey:
                self.logger.critical(
                    "Either generate a new key; or set one. Not both. Aborting."
                )
                sys.exit(1)

            privatekey, publickey = ed25519.create_keypair()

            if self.cnf.privatekeyfile:
                if os.path.isfile(self.cnf.privatekeyfile):
                    self.logger.critical(
                        "Refusing to overwrite existing private key. Aborting."
                    )
                    sys.exit(1)

                if 32 != open(self.cnf.privatekeyfile, "wb").write(
                        privatekey.to_seed()):
                    self.logger.critical(
                        "Failed to write the newly generated privatekeyfile. Aborting."
                    )
                    sys.exit(1)

                self.logger.info("Wrote out newly generated private key")
            else:
                self.logger.info("Using empheral private key")

        if self.cnf.privatekey:
            seed = base64.b64decode(self.cnf.privatekey)

            if len(seed) != 32:
                self.logger.critical(
                    "Command line private key not exactly 32 bytes. aborting.")
                sys.exit(1)
                self.cnf.privatekey = ed25519.SigningKey(seed)
        else:
            if self.cnf.privatekeyfile:
                seed = open(self.cnf.privatekeyfile, "rb").read(32)

                if len(seed) != 32:
                    self.logger.critical(
                        "Private key in file is not exactly 32 bytes. aborting."
                    )
                    sys.exit(1)

        self.cnf.privatekey = ed25519.SigningKey(seed)

        if self.cnf.tofconly and not self.cnf.privatekey:
            self.logger.critical("No private key - cannot do TOFC . Aborting.")
            sys.exit(1)

        self.cnf.publickey = self.cnf.privatekey.get_verifying_key()
        self.pubkeys[self.cnf.node] = self.cnf.publickey

        self.session_priv = curve.generatePrivateKey(Random.new().read(32))
        self.session_pub = curve.generatePublicKey(self.session_priv)
Exemple #4
0
def sign_hash(hash_in):
    print('Signing ' + hash_in)
    keydata = open("root_signing.key", "rb").read()
    signing_key = ed25519.SigningKey(keydata)
    seed = open("root_signing.seed", "rb").read()
    signing_key2 = ed25519.SigningKey(seed)
    sig = signing_key.sign(hash_in, encoding="hex")
    print "sig is:", sig
    verify_sig(sig, hash_in)
    write_ticket(signing_key.get_verifying_key().to_ascii(encoding="hex"), sig,
                 hash_in)
    pass
    def test() -> None:
        recipient: ed25519.SigningKey = ed25519.SigningKey(b'\1' * 32)
        recipientPub: bytes = recipient.get_verifying_key().to_bytes()
        address: str = bech32_encode(
            "mr", convertbits(bytes([0]) + recipientPub, 8, 5))

        otherRecipient: bytes = ed25519.SigningKey(
            b'\2' * 32).get_verifying_key().to_bytes()
        otherAddress: str = bech32_encode(
            "mr", convertbits(bytes([0]) + otherRecipient, 8, 5))

        #Create a Send.
        send: Send = Send.fromJSON(vectors["send"])
        if rpc.meros.liveTransaction(send) != rpc.meros.live.recv():
            raise TestError("Meros didn't broadcast back a Send.")
        if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
            raise TestError(
                "Meros considered an unconfirmed Transaction's outputs as UTXOs."
            )
        verify(rpc, send.hash)

        #Spend it.
        spendingSend: Send = Send.fromJSON(vectors["spendingSend"])
        if rpc.meros.liveTransaction(spendingSend) != rpc.meros.live.recv():
            raise TestError("Meros didn't broadcast back a Send.")
        if rpc.call("transactions", "getUTXOs", {"address": address}) != []:
            raise TestError(
                "Meros didn't consider a Transaction's inputs as spent.")

        #Verify with another party, so it won't be majority verified, yet will still have a Verification.
        mineBlock(rpc, 1)
        verify(rpc, spendingSend.hash, 1)
        #Verify it didn't create a UTXO.
        if rpc.call("transactions", "getUTXOs",
                    {"address": otherAddress}) != []:
            raise TestError("Unverified Transaction created a UTXO.")

        #Finalize.
        for _ in range(6):
            mineBlock(rpc)

        #Check the UTXOs were created.
        if rpc.call("transactions", "getUTXOs", {"address": otherAddress}) != [
            {
                "hash": spendingSend.hash.hex().upper(),
                "nonce": 0
            }
        ]:
            raise TestError(
                "Meros didn't consider a finalized Transaction's outputs as UTXOs."
            )

        raise SuccessError()
 def test_publickey(self):
     seed = unhexlify("4ba96b0b5303328c7405220598a587c4"
                      "acb06ed9a9601d149f85400195f1ec3d")
     sk = ed25519.SigningKey(seed)
     self.failUnlessEqual(hexlify(sk.to_bytes()),
                          (b"4ba96b0b5303328c7405220598a587c4"
                           b"acb06ed9a9601d149f85400195f1ec3d"
                           b"a66d161e090652b054740748f059f92a"
                           b"5b731f1c27b05571f6d942e4f8b7b264"))
     self.failUnlessEqual(hexlify(sk.to_seed()),
                          (b"4ba96b0b5303328c7405220598a587c4"
                           b"acb06ed9a9601d149f85400195f1ec3d"))
     self.failUnlessRaises(ValueError, ed25519.SigningKey, b"wrong length")
     sk2 = ed25519.SigningKey(seed)
     self.failUnlessEqual(sk, sk2)
Exemple #7
0
def createSend(rpc: RPC, claim: Claim, to: bytes) -> bytes:
    send: Send = Send([(claim.hash, 0)], [(to, claim.amount)])
    send.sign(ed25519.SigningKey(b'\0' * 32))
    send.beat(SpamFilter(3))
    if rpc.meros.liveTransaction(send) != rpc.meros.live.recv():
        raise TestError("Meros didn't send back a Send.")
    return send.hash
Exemple #8
0
 def private_to_public(private: str) -> str:
     """Temp Test"""
     keydata = bytes.fromhex(private)
     signing_key = ed25519.SigningKey(keydata)
     verifying_key = signing_key.get_verifying_key()
     vkey_hex = verifying_key.to_ascii(encoding="hex")
     return vkey_hex.decode('utf-8')
Exemple #9
0
 def get_from_private_seed_file(filename: str):
     """returns priv and pub key - as object - from the stored nyzo text id format"""
     with open(filename) as f:
         nyzo = f.read(80).replace('-', '').encode('utf-8').strip()
         signing_key = ed25519.SigningKey(nyzo, encoding="hex")
         verifying_key = signing_key.get_verifying_key()
     return signing_key, verifying_key
    def test_encoding(self):
        sk_s = b"\x88" * 32  # usually urandom(32)
        sk1 = ed25519.SigningKey(sk_s)
        vk1 = sk1.get_verifying_key()

        def check1(encoding, expected):
            PREFIX = "private0-"
            p = sk1.to_ascii(PREFIX, encoding)
            self.failUnlessEqual(p, expected)
            sk2 = ed25519.SigningKey(p, prefix=PREFIX, encoding=encoding)
            self.failUnlessEqual(repr(sk1.to_bytes()), repr(sk2.to_bytes()))
            self.failUnlessEqual(sk1, sk2)

        check1("base64",
               b"private0-iIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIg")
        check1(
            "base32",
            b"private0-rceirceirceirceirceirceirceirceirceirceirceirceircea")
        check1(
            "hex",
            b"private0-8888888888888888888888888888888888888888888888888888888888888888"
        )

        def check2(encoding, expected):
            PREFIX = "public0-"
            p = vk1.to_ascii(PREFIX, encoding)
            self.failUnlessEqual(p, expected)
            vk2 = ed25519.VerifyingKey(p, prefix=PREFIX, encoding=encoding)
            self.failUnlessEqual(repr(vk1.to_bytes()), repr(vk2.to_bytes()))
            self.failUnlessEqual(vk1, vk2)

        check2("base64",
               b"public0-skkdlQKuKGMKK6yy4MdFEP/N0yjDNP8+E5PnWy0x59w")
        check2(
            "base32",
            b"public0-wjer3ficvyuggcrlvszobr2fcd743uziym2p6pqtsptvwljr47oa")
        check2(
            "hex",
            b"public0-b2491d9502ae28630a2bacb2e0c74510ffcdd328c334ff3e1393e75b2d31e7dc"
        )

        def check3(encoding, expected):
            msg = b"msg"
            PREFIX = "sig0-"
            sig = sk1.sign(msg, PREFIX, encoding)
            self.failUnlessEqual(sig, expected)
            vk1.verify(sig, msg, PREFIX, encoding)

        check3(
            "base64",
            b"sig0-MNfdUir6tMlaYQ+/p8KANJ5d+bk8g2al76v5MeJCo6RiywxURda3sU580CyiW2FBG/Q7kDRswgYqxbkQw3o5CQ"
        )
        check3(
            "base32",
            b"sig0-gdl52urk7k2mswtbb672pquagspf36nzhsbwnjppvp4tdyscuosgfsymkrc5nn5rjz6nalfclnqucg7uhoidi3gcayvmloiqyn5dsci"
        )
        check3(
            "hex",
            b"sig0-30d7dd522afab4c95a610fbfa7c280349e5df9b93c8366a5efabf931e242a3a462cb0c5445d6b7b14e7cd02ca25b61411bf43b90346cc2062ac5b910c37a3909"
        )
 def check1(encoding, expected):
     PREFIX = "private0-"
     p = sk1.to_ascii(PREFIX, encoding)
     self.failUnlessEqual(p, expected)
     sk2 = ed25519.SigningKey(p, prefix=PREFIX, encoding=encoding)
     self.failUnlessEqual(repr(sk1.to_bytes()), repr(sk2.to_bytes()))
     self.failUnlessEqual(sk1, sk2)
Exemple #12
0
    def load_secrets(self) -> None:
        if not config.get("ed25519.signing_key"):
            # Generating keys on demand. This is useful for unit tests
            self.signing_key, self.verifying_key = ed25519.create_keypair(
                entropy=os.urandom
            )
            return

        signing_key_file = os.path.expanduser(config.get("ed25519.signing_key"))
        try:
            with open(signing_key_file, "rb") as signing_file:
                signing_key_str: str = signing_file.read()
        except FileNotFoundError:
            msg = "Unable to load signing key"
            log.error(msg, exc_info=True)
            raise Exception(msg)
        self.signing_key = ed25519.SigningKey(signing_key_str)
        verifying_key_file = config.get("ed25519.verifying_key")
        try:
            verifying_key_str = open(verifying_key_file, "rb").read()
        except FileNotFoundError:
            msg = "Unable to load verifying key"
            log.error(msg, exc_info=True)
            raise Exception(msg)
        self.verifying_key = ed25519.VerifyingKey(verifying_key_str)
Exemple #13
0
 def from_seed(self,
               seed: str = '',
               subtype: SignerSubType = SignerSubType.MAINNET_REGULAR):
     """Creates key from seed - for ED25519, seed = pk - 32 bytes random buffer"""
     if subtype != SignerSubType.MAINNET_REGULAR:
         self._subtype = subtype
     if len(seed) > 64:
         # Too long seed, trim (could use better scheme for more entropy)
         seed = seed[:64]
     elif seed == '':
         # No seed, use urandom
         seed = urandom(32)
     elif len(seed) < 64:
         # Too short seed, use as PRNG seed
         random.seed(seed)
         seed = random.getrandbits(32 * 8).hex()
     try:
         print("SEED", seed)
         # TODO: check flow, there may be many unnecessary hex-byte-hex-bytes conversions from top to bottom
         key = ed25519.SigningKey(bytes.fromhex(seed))
         hexa = key.to_ascii(encoding="hex").decode('utf-8')
         # print("ED25519 Privk Key", hexa)  # e5b42f3c-3fe02e16-1d42ff47-07a174a5 715b2badc7d4d3aebbea9081bd9123d5
         verifying_key = key.get_verifying_key()
         public_key = verifying_key.to_ascii(encoding="hex").decode('utf-8')
         # public_key = hexa[32:]
         # print("ED25519 Public Key", public_key)
         self._key = key
         self._private_key = hexa
         self._public_key = public_key
     except Exception as e:
         print("Exception {} reading ED25519 private key".format(e))
     # print("identifier", self.identifier().hex())
     self._address = self.address()
Exemple #14
0
def createSend(
    rpc: RPC,
    inputs: List[Union[Claim, Send]],
    to: bytes,
    key: ed25519.SigningKey = ed25519.SigningKey(b'\0' * 32)) -> Send:
    pub: bytes = key.get_verifying_key().to_bytes()
    actualInputs: List[Tuple[bytes, int]] = []
    outputs: List[Tuple[bytes, int]] = [(to, 1)]
    toSpend: int = 0
    for txInput in inputs:
        if isinstance(txInput, Claim):
            actualInputs.append((txInput.hash, 0))
            toSpend += txInput.amount
        else:
            for n in range(len(txInput.outputs)):
                if txInput.outputs[n][0] == key.get_verifying_key().to_bytes():
                    actualInputs.append((txInput.hash, n))
                    toSpend += txInput.outputs[n][1]
    if toSpend > 1:
        outputs.append((pub, toSpend - 1))

    send: Send = Send(actualInputs, outputs)
    send.sign(key)
    send.beat(SpamFilter(3))
    if rpc.meros.liveTransaction(send) != rpc.meros.live.recv():
        raise TestError("Meros didn't broadcast back a Send.")
    return send
    def sign(self, sig_directives, signed) -> list:
        data = self.cjson(signed).encode('utf-8')

        sigs = []
        for (priv, pub), bad_sig in sig_directives:
            if self.signature_scheme == 'ed25519':
                priv = ed25519.SigningKey(binascii.unhexlify(priv))
                sig = priv.sign(data)
            elif self.signature_scheme.startswith('rsa'):
                if self.signature_scheme == 'rsassa-pss-sha256':
                    h = SHA256.new(data)
                elif self.signature_scheme == 'rsassa-pss-sha512':
                    h = SHA512.new(data)
                else:
                    raise Exception('Unknown signature scheme: {}'.format(
                        self.signature_scheme))

                rsa = RSA.importKey(priv)
                signer = PKCS1_PSS.new(rsa)
                sig = signer.sign(h)
            else:
                raise Exception('Unknow signature scheme: {}'.format(
                    self.signature_scheme))

            if bad_sig:
                sig[0] ^= 0x01

            sig_data = {
                'keyid': self.key_id(pub, bad_id=False),
                'method': self.signature_scheme,
                'sig': self.encode_signature(sig),
            }
            sigs.append(sig_data)

        return sigs
Exemple #16
0
    def create_account(self, member, bank_code, access_id, name):
        """
        Creates a new account for a given member. Before calling this method
        caller needs to obtain authorization to link the account using bank
        API.

        :param member: used to authenticate and identify user making the request
        :type member: Member
        :param bank_code: code that identifies that bank that issued account
            linking authorization
        :type bank_code: str
        :param access_id: bank issued account access id. The id will be used to
            identify the account when making bank calls.
        :type access_id: str
        :param name: name to associate with the account
        :return: server response
        """
        key = ed25519.SigningKey(
            ed25519.keys.from_ascii(member.secret_key(), encoding="hex"))
        signature = str(codecs.encode(key.sign(str.encode(member.device_id())),
                                      'hex'),
                        encoding="UTF-8")
        request = {
            "bankCode": bank_code,
            "accessId": access_id,
            "verificationSignature": signature,
            "name": name
        }
        auth = create_authorization(member.principal(), 'POST',
                                    self._base_url + '/accounts', request)
        return self._accounts.create_account_route(request, authorization=auth)
Exemple #17
0
def test_ed25519():
    sk = ed25519.SigningKey(b'\x00' * 32)
    vk = sk.get_verifying_key()
    pk = proto.PublicKey(curve_name=formats.CURVE_ED25519,
                         created=42,
                         verifying_key=vk)
    assert repr(pk) == 'GPG public key ed25519/36B40FE6'
Exemple #18
0
    def m1_generate_verify_start_request(self) -> List[Tuple[int, bytes]]:
        """Generate the SRP Start request message TLVs.

        The message contains 2 TLVs:
        - Return_Response: 1
        - Vale: kTLVs

        With the kTLVs:
        - kTLVType_State <M1>
        - kTLVType_PublicKey <Curve25519 public key>
        """
        with open(os.path.join(self.storage_folder, "secret-key"),
                  "rb") as secret_key_file:
            self.secret_key = ed25519.SigningKey(secret_key_file.read())
        self.verifying_key = self.secret_key.get_verifying_key()

        ktlvs = [(constants.PairingKTlvValues.kTLVType_State, pack('<B', 1)),
                 (constants.PairingKTlvValues.kTLVType_PublicKey,
                  self.verifying_key.to_bytes())]

        prepared_ktlvs = b''.join(
            data for ktlv in ktlvs for data in utils.prepare_tlv(*ktlv))

        message_data = [(constants.HapParamTypes.Return_Response, pack(
            '<B', 1)), (constants.HapParamTypes.Value, prepared_ktlvs)]

        return message_data
Exemple #19
0
 def create_transaction_with_smart_contract(self, code, fee, keys):
     tr = Transaction()
     contract = SmartContractInvocation()
     contract.smartContractDeploy = SmartContractDeploy()
     if code == "":
         code = 'import com.credits.scapi.annotations.*; import com.credits.scapi.v0.*; public class ' \
                'MySmartContract extends SmartContract { public MySmartContract() {} public String hello2(String ' \
                'say) { return \"Hello\" + say; } }'
     contractText = self.normalizeCode(code)
     result = self.compile_smart(contractText)
     contract.smartContractDeploy.byteCodeObjects = result.byteCodeObjects
     tr.smartContract = contract
     tr.smartContract.smartContractDeploy.sourceCode = contractText
     tr.source = keys.public_key_bytes
     w = self.client.WalletTransactionsCountGet(tr.source)
     lastInnerId = bytearray(
         (w.lastTransactionInnerId + 1).to_bytes(6, 'little'))
     tr.id = int.from_bytes(lastInnerId, byteorder='little', signed=False)
     tr.target = self.createContractAddress(tr.source, lastInnerId,
                                            contract)
     tr.amount = Amount()
     tr.amount.integral = 0
     tr.amount.fraction = 0
     tr.balance = Amount()
     tr.balance.integral = 0
     tr.balance.fraction = 0
     tr.currency = 1
     tr.fee = AmountCommission()
     tr.fee.commission = self.double_to_fee(fee)
     tr.userFields = ""
     ufNum1 = bytearray(b'\x01')
     contract.smartContractDeploy.hashState = ""
     contract.smartContractDeploy.tokenStandard = 0
     contract.method = ""
     contract.params = []
     contract.usedContracts = []
     contract.forgetNewState = False
     transportOut = TMemoryBuffer()
     protocolOut = TBinaryProtocol(transportOut)
     contract.write(protocolOut)
     scBytes = transportOut.getvalue()
     sMap = '=6s32s32slqhb1s4s' + str(
         len(scBytes)
     ) + 's'  #4s' + str(scriptLength) + 's4s' + str(codeNameLength) + 's4s' + str(codeLength) + 's' #len(userField_bytes)
     serial_transaction_for_sign = pack(
         sMap,  #'=' - without alignment
         lastInnerId,  #6s - 6 byte InnerID (char[] C Type)
         tr.source,  #32s - 32 byte source public key (char[] C Type)
         tr.target,  #32s - 32 byte target pyblic key (char[] C Type)
         tr.amount.integral,  #i - 4 byte integer(int C Type)
         tr.amount.fraction,  #q - 8 byte integer(long long C Type)
         tr.fee.commission,  #h - 2 byte integer (short C Type)
         tr.currency,  #b - 1 byte integer (signed char C Type)
         ufNum1,
         bytes(len(scBytes).to_bytes(4, byteorder="little")),
         scBytes)
     signing_key = ed25519.SigningKey(
         keys.private_key_bytes)  # Create object for calulate signing
     tr.signature = signing_key.sign(serial_transaction_for_sign)
     return tr
Exemple #20
0
    def _gen_keypack(self, name):
        app_pri, app_pub = self._make_keys()
        off_pri, off_pub = self._load_offline_keys(name)
        log.debug('off_pri type: %s', off_pri)

        off_pri = off_pri.encode()
        if six.PY2:
            app_pub = six.b(app_pub)
            log.debug('off_pri type: %s', type(off_pri))
        signing_key = ed25519.SigningKey(off_pri, encoding='base64')

        signature = signing_key.sign(app_pub, encoding='base64').decode()

        if six.PY3:
            app_pri = app_pri.decode()
            app_pub = app_pub.decode()

        keypack = {
            'upload': {
                'app_public': app_pub,
                'signature': signature
            },
            'client': {
                'offline_public': off_pub
            },
            'repo': {
                'app_private': app_pri
            }
        }
        return keypack
Exemple #21
0
 def derive_public_key(self) -> PublicKey:
     """
     Derives and returns the public key.
     """
     sk = ed25519.SigningKey(bytes(self))
     vk = sk.get_verifying_key()
     return PublicKey(vk.to_bytes())
Exemple #22
0
    def _add_sig(self):
        # Adding new signature to version file
        private_keys = self._load_private_keys()
        # Just making sure we have a least 2 keys so when revoke is
        # called we have a fall back
        if len(private_keys) < 2:
            self.make_keys()
        private_keys = self._load_private_keys()

        update_data = self._load_update_data()
        if 'sigs' in update_data:
            log.debug('Removing signatures from version file')
            del update_data['sigs']
        update_data_str = json.dumps(update_data, sort_keys=True)

        signatures = []
        for p in private_keys:
            if six.PY2 is True and isinstance(p, unicode) is True:
                log.debug('Got type: {}'.format(type(p)))
                p = str(p)
            log.debug('Key type: {}'.format(type(p)))
            privkey = ed25519.SigningKey(p, encoding=self.key_encoding)
            # Signs update data with private key
            sig = privkey.sign(six.b(update_data_str),
                               encoding=self.key_encoding)
            log.debug('Sig: {}'.format(sig))
            signatures.append(sig)

        og_data = json.loads(update_data_str)
        update_data = og_data.copy()
        # Add signatures to update data
        update_data['sigs'] = signatures
        log.info('Adding sig to update data')
        # Write updated version file to filesystem
        self._write_update_data(og_data, update_data)
Exemple #23
0
 def sign(self, message: bytes) -> Signature:
     """
     Signs the provided message with the private key and returns the signature.
     """
     sk = ed25519.SigningKey(bytes(self))
     digest = hashlib.sha256(message).digest()
     return Signature(sk.sign(digest))
Exemple #24
0
def _signing_key(name, prefix=None):
    """
    helper to load signing keys from filesystem
    NOTE: keys must already be present  see: ./src/gen_keys.py
    """
    keydata = open(prefix + name + "-secret-key.txt", "rb").read()
    return ed25519.SigningKey(keydata)
Exemple #25
0
    def create_transaction(self, integral, fraction, fee, keys):
        tr = Transaction()
        tr.id = self.client.WalletTransactionsCountGet(keys.public_key_bytes).lastTransactionInnerId + 1
        tr.source = keys.public_key_bytes
        tr.target = keys.target_public_key_bytes
        tr.amount = Amount()
        tr.amount.integral = integral
        tr.amount.fraction = fraction
        tr.currency = 1

        tr.fee = AmountCommission()
        tr.fee.commission = self.__fee(fee)

        serial_transaction = pack('=6s32s32slqhbb',                       # '=' - without alignment'
                                  bytearray(tr.id.to_bytes(6, 'little')), # 6s - 6 byte InnerID (char[] C Type)
                                  tr.source,                              # 32s - 32 byte source public key (char[] C Type)
                                  tr.target,                              # 32s - 32 byte target pyblic key (char[] C Type)
                                  tr.amount.integral,                     # i - 4 byte integer(int C Type)
                                  tr.amount.fraction,                     # q - 8 byte integer(long long C Type)
                                  tr.fee.commission,                      # h - 2 byte integer (short C Type)
                                  tr.currency,                            # b - 1 byte integer (signed char C Type)
                                  0                                       # b - 1 byte userfield_num
        )

        signing_key = ed25519.SigningKey(keys.private_key_bytes)
        sign = signing_key.sign(serial_transaction)
        tr.signature = sign

        return tr
Exemple #26
0
def sign(op, private):
    signing_key = ed25519.SigningKey(base64.b64decode(private))
    message = json.dumps(op, sort_keys=True,
                         separators=(',', ':')).encode('ascii')
    sig = signing_key.sign(message)
    sig = base64.b64encode(sig).decode('ascii')
    return sig
def main():
    private_key = None
    algo = ES256
    with open(sys.argv[1], 'rb') as fd:
        priv_key_bytes = fd.read()
        try:
            private_key = serialization.load_pem_private_key(
                priv_key_bytes, password=None, backend=default_backend())
        except ValueError:
            algo = EDDSA
            private_key = ed25519.SigningKey(
                eddsa.parse_privkey(priv_key_bytes))

    public_key = None
    with open(sys.argv[2], 'rb') as fd:
        pub_key_bytes = fd.read()
        try:
            public_key = serialization.load_pem_public_key(
                pub_key_bytes, backend=default_backend())
        except ValueError:
            public_key = ed25519.VerifyingKey(
                eddsa.parse_pubkey(pub_key_bytes))

    # Read the input file
    doc = None
    with open(sys.argv[3], 'rb') as fd:
        doc = fd.read()

    outDoc = signWrapper(algo, private_key, public_key, doc)

    with open(sys.argv[4], 'wb') as fd:
        fd.write(cbor.dumps(outDoc, sort_keys=True))
Exemple #28
0
def create_keypair(algo, seed=None):

   assert algo in ["ed25519", "ecdsa_p256", "ecdsa_p384"], "invalid algorithm"

   if algo == "ed25519":
      if seed:
         signing_key = ed25519.SigningKey(seed, encoding="hex")
         verifying_key = signing_key.get_verifying_key()
      else:
         signing_key, verifying_key = ed25519.create_keypair()
      return signing_key.to_seed(), verifying_key.to_bytes()

   if "ecdsa" in algo:
      if algo == "ecdsa_p256":
         curve=ecdsa.NIST256p
      elif algo == "ecdsa_p384":
         curve=ecdsa.NIST384p

      if seed:
         seedbytes = binascii.unhexlify(seed)
         signing_key = ecdsa.SigningKey.from_string(seedbytes, curve=curve)
      else:
         signing_key = ecdsa.SigningKey.generate(curve=curve)
      verifying_key = signing_key.get_verifying_key()
      return signing_key.to_string(), verifying_key.to_string()
Exemple #29
0
def add_address():
    timestamp = str(int(time.time() * 1000))

    data = {
        "chain": chain,
        "addr_list": ["BAAS-TEST-address-123456", "BAAS-TEST-address-654321"]
    }
    sign_msg = create_sign_msg("POST", "/api/v1/address/add", timestamp, data)

    signing_key = ed25519.SigningKey(private_key, "", "hex")
    signature = signing_key.sign(sign_msg)
    print("signature = ", hexlify(signature))

    headers = {
        "BWAAS-API-KEY": api_key,
        "BWAAS-API-TIMESTAMP": timestamp,
        "BWAAS-API-SIGNATURE": hexlify(signature),
        "Content-Type": "application/json"
    }

    res = requests.post(url=domain + "/api/v1/address/add",
                        data=json.dumps(data),
                        headers=headers)

    print(res.text)
Exemple #30
0
def export_pubkey(seckey='keypair.dat', pubkey='pubkey.json', owner_name='root'):
    keydata = open(seckey, 'rb').read()
    sk = ed25519.SigningKey(keydata)
    vk = sk.get_verifying_key()
    vk_s = vk.to_ascii(encoding='hex')
    dt_now = datetime.datetime.now()
    dt_now = TZ.localize(dt_now)
    dt_exp = dt_now + datetime.timedelta(days=365)
    data = {
        'envelope': {
            'date': dt_now.isoformat(),
            'model': 'admin/pubkey',
            'owner': owner_name,
            'payload': {
                'algorithm': 'Ed25519',
                'owner': owner_name,
                'publicKey': vk_s.decode(),
                'validSince': dt_now.isoformat(),
                'validTill': dt_exp.isoformat()
            }
        }
    }
    data_sign(data, sk)
    data_s = dump_pretty(data)
    with open(pubkey, 'wb') as fp:
        fp.write(data_s)
    print('Public verifying key saved to', pubkey)