当前位置: 首页>>代码示例>>Python>>正文


Python SigningKey.from_der方法代码示例

本文整理汇总了Python中ecdsa.SigningKey.from_der方法的典型用法代码示例。如果您正苦于以下问题:Python SigningKey.from_der方法的具体用法?Python SigningKey.from_der怎么用?Python SigningKey.from_der使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ecdsa.SigningKey的用法示例。


在下文中一共展示了SigningKey.from_der方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
def main(argv):

    """
        Main procedure to generate C array with keys
    """

    parser = argparse.ArgumentParser(description="Generates SQLite database with"
        " keys and serial number.")
    parser.add_argument('config_file', help="project specific configuration file"
        )
    args = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.read(args.config_file)
    con = sqlite3.connect(config.get('database', 'filename'))

    while 1:
        serialno = uuid.uuid4().bytes
        oem_factory_token = '%s%s' %(serialno, '\xFF')
        customer_factory_token = '%s%s' %(serialno, '\x00\xFF')

        private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        public_key = generate_public_key(config.get('tools', 'public_key_cmd'), private_key)
        sk = SigningKey.from_der(private_key)
        pk = VerifyingKey.from_der(public_key)

        embedded_private_key = generate_private_key(config.get('tools', 'private_key_cmd'))
        embedded_public_key = generate_public_key(config.get('tools', 'public_key_cmd'), embedded_private_key)
        embedded_sk = SigningKey.from_der(embedded_private_key)
        embedded_pk = VerifyingKey.from_der(embedded_public_key)

        embedded_private_key_sig = embedded_sk.sign(oem_factory_token, hashfunc=sha256)
        assert embedded_pk.verify(embedded_private_key_sig, oem_factory_token, hashfunc=sha256)

        oem_factory_token_sig = sk.sign(oem_factory_token, hashfunc=sha256)
        assert pk.verify(oem_factory_token_sig, oem_factory_token, hashfunc=sha256)

        customer_factory_token_sig = sk.sign(customer_factory_token, hashfunc=sha256)
        assert pk.verify(customer_factory_token_sig, customer_factory_token, hashfunc=sha256)

        debug_token_sig = sk.sign(serialno, hashfunc=sha256)
        assert pk.verify(debug_token_sig, serialno, hashfunc=sha256)

        public_key_compressed = ecc_compress(pk.to_string())

        with con:
            cur = con.cursor()
            cur.execute(config.get('database', 'create'))
            cur.execute(config.get('database', 'insert'),
                        (sqlite3.Binary(private_key),
                         sqlite3.Binary(public_key),
                         sqlite3.Binary(public_key_compressed),
                         sqlite3.Binary(embedded_private_key),
                         sqlite3.Binary(embedded_public_key),
                         sqlite3.Binary(embedded_sk.to_string()),
                         sqlite3.Binary(serialno),
                         sqlite3.Binary(oem_factory_token_sig),
                         sqlite3.Binary(customer_factory_token_sig),
                         sqlite3.Binary(debug_token_sig)))
开发者ID:CurieBSP,项目名称:main,代码行数:61,代码来源:generate_factory_database.py

示例2: _decode_key

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
 def _decode_key(self, data):
     s, padding = der.remove_sequence(data)
     if padding:
         if padding not in self.ALLOWED_PADDINGS:
             raise ValueError("weird padding: %s" % u(binascii.hexlify(data)))
         data = data[:-len(padding)]
     key = SigningKey.from_der(data)
     self.signing_key = key
     self.verifying_key = key.get_verifying_key()
     self.size = 256
开发者ID:Rachitlohani,项目名称:paramiko,代码行数:12,代码来源:ecdsakey.py

示例3: main

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
def main(argv):

    """
        Main procedure to sign a binary
    """


    parser = argparse.ArgumentParser(description='tool to sign binaries using ECDSA')
    parser.add_argument('-s','--privkey_file', help='Private key', required=True)
    parser.add_argument('-i','--input_file', help='File to sign', required=True)
    parser.add_argument('-o','--output_file', help='Signed output', required=True)
    parser.add_argument('-f','--ota_package', help='OTA package', required=True, default=0)
    args = parser.parse_args()

    privkey_file = args.privkey_file
    input_file = args.input_file
    output_file = args.output_file
    ota_package = int(args.ota_package)


    privkey = SigningKey.from_der(open(privkey_file).read())

    fd = open(input_file, "rb")
    if ota_package == 0:
        fd.seek(0x80)
    message = bytearray(fd.read())
    fd.close()

    # align on 4 bytes
    if len(message) % 4 != 0:
        message += bytearray.fromhex("ff" * (4 - (len(message) % 4)))

    signature = bytearray(privkey.sign(message, hashfunc=sha256))
    assert len(signature) == 64

    sigheader = SigHeader("$SIG", 0x01, 0x00, 0x00, len(message))
    sigheader.signature[0:64] = signature[0:64]
    sigheader.reserved1[0:52] = [0] * 52
    arr = bytearray(sigheader)
    assert len(arr) == 128
    arr[0x80:0x80+len(message)] = message

    sigfile = open(output_file, "wb")
    sigfile.write(arr)
    sigfile.close()
开发者ID:CurieBSP,项目名称:main,代码行数:47,代码来源:sign.py

示例4: main

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
def main(argv):

    """
        Main procedure to sign a binary
    """


    parser = argparse.ArgumentParser(description='convert der to raw')
    parser.add_argument('-s','--secretkey_file', help='Secret key', required=True)
    parser.add_argument('-p','--publickey_file', help='Public key', required=True)
    args = parser.parse_args()

    secretkey_file = args.secretkey_file
    publickey_file = args.publickey_file


    privkey = SigningKey.from_der(open(secretkey_file).read())
    pubkey = VerifyingKey.from_der(open(publickey_file).read())

    open(secretkey_file[0:-4] + ".bin", "wb").write(privkey.to_string())
    open(publickey_file[0:-4] + ".bin", "wb").write(pubkey.to_string())
开发者ID:CurieBSP,项目名称:main,代码行数:23,代码来源:der2binary.py

示例5: sign

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
def sign(prvKey, message):
    sk = SigningKey.from_der(prvKey)
    hashed = _policy_[sk.curve.name][1](message).digest()
    signature = sk.sign(hashed)
    return signature
开发者ID:loesung,项目名称:kern.geheimdienst,代码行数:7,代码来源:ec.dsa.py

示例6: process_request

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
def process_request(netki_client, uri, method, data=''):
    """
    API request processor handling supported API methods and error messages returned from API. Refer to the Netki
    Apiary documentation for additional information. http://docs.netki.apiary.io/

    :param netki_client: Netki client reference
    :param uri: api_url from Netki class init
    :param method: Request method
    :param data: PUT / POST data
    :return: AttrDict for valid, non-error responses. Empty dict for 204 responses. Exception for error responses.
    """

    if method not in ['GET', 'POST', 'PUT', 'DELETE']:
        raise Exception('Unsupported HTTP method: %s' % method)

    headers = {}
    if data:
        headers['Content-Type'] = 'application/json'
        data = json.dumps(data)

    if netki_client._auth_type == 'api_key':
        headers.update({
            'Authorization': netki_client.api_key,
            'X-Partner-ID': netki_client.partner_id
        })

    elif netki_client._auth_type == 'distributed':

        key = SigningKey.from_der(netki_client.user_key.decode('hex'))

        encoded_user_pub_key = key.get_verifying_key().to_der().encode('hex')
        encoded_data_sig = key.sign(
            netki_client.api_url + uri + data,
            hashfunc=hashlib.sha256, sigencode=sigencode_der
        ).encode('hex')

        headers.update({
            'X-Partner-Key': netki_client.key_signing_key,
            'X-Partner-KeySig': netki_client.signed_user_key,
            'X-Identity': encoded_user_pub_key,
            'X-Signature': encoded_data_sig
        })

    elif netki_client._auth_type == 'certificate':

        key = SigningKey.from_der(netki_client.user_key.decode('hex'))

        encoded_user_pub_key = key.get_verifying_key().to_der().encode('hex')
        encoded_data_sig = key.sign(netki_client.api_url + uri + data, hashfunc=hashlib.sha256, sigencode=sigencode_der).encode('hex')

        headers.update({
            'X-Identity': encoded_user_pub_key,
            'X-Signature': encoded_data_sig,
            'X-Partner-ID': netki_client.partner_id
        })

    else:
        raise Exception('Invalid Access Type Defined')

    response = requests.request(method=method, url=netki_client.api_url + uri, headers=headers, data=data if data else None)

    if method == 'DELETE' and response.status_code == 204:
        return {}

    rdata = AttrDict(response.json())

    if response.status_code >= 300 or not rdata.success:
        error_message = rdata.message

        if 'failures' in rdata:
            error_message += ' [FAILURES: '
            failures = []
            for failure in rdata.failures:
                failures.append(failure.message)

            error_message = error_message + ', '.join(failures) + ']'

        raise Exception(error_message)

    return rdata
开发者ID:netkicorp,项目名称:python-partner-api-client,代码行数:82,代码来源:Requestor.py

示例7: print

# 需要导入模块: from ecdsa import SigningKey [as 别名]
# 或者: from ecdsa.SigningKey import from_der [as 别名]
# Miner initialisation

try:
    opts, args = getopt.getopt(sys.argv[1:], "hmk:")
except getopt.GetoptError:
    print(sys.argv[0], "[-m] [-k <private key>]")
    sys.exit(2)

private_key = None

for opt, arg in opts:
    if opt == '-h':
        print(sys.argv[0], "[-m] [-k <private key>]")
        sys.exit()
    elif opt == '-k':
        private_key = SigningKey.from_der(binascii.unhexlify(arg))
    elif opt == '-m':
        is_miner = True

if private_key is None:
    private_key = SigningKey.generate()
    print("Private key:")
    print(binascii.hexlify(private_key.to_der()).decode())

user = User(private_key)

print("Starting...")

# Asyncio

loop = asyncio.get_event_loop()
开发者ID:CeON,项目名称:pmpi,代码行数:33,代码来源:pmpi-cli.py


注:本文中的ecdsa.SigningKey.from_der方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。