def _build_signature(key, certreqinfo, network): secret_exponent = encoding.to_long(256, encoding.byte_to_int, key[0][1].asOctets())[0] coin = Key(secret_exponent=secret_exponent, netcode=network) print "building signature for %s address: %s" % (network, coin.address()) pubkeybitstring = (key[0].getComponentByPosition(2), key[0].getComponentByPosition(3)) certreqinfoder = encoder.encode(certreqinfo) hashvalue = SHA256.new(certreqinfoder) dgst = hashvalue.digest() dgstaslong = encoding.to_long(256, encoding.byte_to_int, dgst)[0] order2 = pycoin.ecdsa.generator_secp256k1.order() ## random sign generator = pycoin.ecdsa.generator_secp256k1 rawsig2 = randomsign(generator, secret_exponent, dgstaslong) ## deterministic sign ##rawsig2 = pycoin.ecdsa.sign(pycoin.ecdsa.generator_secp256k1, secret_exponent, dgstaslong) r2, s2 = rawsig2 print "signature: r: %x s: %x" % (r2, s2) if not pycoin.ecdsa.verify(generator, coin.public_pair(), dgstaslong, rawsig2): raise SignatureVerifyException("Generated signature r: %x s: %x does not verify against public key %s" % (r2, s2, public_pair)) signature = ECDSASigValue() signature.setComponentByName('r', r2) signature.setComponentByName('s', s2) dersig = encoder.encode(signature) signaturevalue = "'{0}'H".format(binascii.hexlify(dersig)) bitstring = univ.BitString( value=signaturevalue ) return rfc2314.Signature( bitstring )
def _build_signature(key, tbs, network): ''' Takes a utility.ECPrivateKey() as key, tbs as rfc2459.TBSCertificate, and network as pycoin.NETWORK_NAMES ''' secret_exponent = encoding.to_long(256, encoding.byte_to_int, key[0][1].asOctets())[0] coin = Key(secret_exponent=secret_exponent, netcode=network) public_pair = coin.public_pair() coin_address = coin.address() print "building signature for %s address %s" % (network, coin_address) pubkeybitstring = (key[0].getComponentByPosition(2), key[0].getComponentByPosition(3)) tbsder = encoder.encode(tbs) hashvalue = SHA256.new(tbsder) dgst = hashvalue.digest() dgstaslong = encoding.to_long(256, encoding.byte_to_int, dgst)[0] order2 = pycoin.ecdsa.generator_secp256k1.order() ## random sign generator = pycoin.ecdsa.generator_secp256k1 rawsig2 = randomsign(generator, secret_exponent, dgstaslong) # deterministic sign ##rawsig2 = pycoin.ecdsa.sign(pycoin.ecdsa.generator_secp256k1, secret_exponent, dgstaslong) r2, s2 = rawsig2 print "signature: r: %x s: %x" % (r2, s2) if not pycoin.ecdsa.verify(generator, coin.public_pair(), dgstaslong, rawsig2): raise SignatureVerifyException( "Generated signature r: %x s: %x does not verify against public key %s" % (r2, s2, public_pair)) signature = utility.ECDSASigValue() signature.setComponentByName('r', r2) signature.setComponentByName('s', s2) dersig = encoder.encode(signature) signaturevalue = "'{0}'H".format(binascii.hexlify(dersig)) bitstring = univ.BitString(value=signaturevalue) return rfc2314.Signature(bitstring)
def randomsign(generator, secret_exponent, val): # from https://github.com/richardkiss/pycoin/blob/master/pycoin/ecdsa/ecdsa.py # but randomized sig. Use k value in the order of the curve from math import log G = generator n = G.order() n_bytes = int(log(n)) + 7 // 8 rndfile = Random.new() k = encoding.to_long(256, encoding.byte_to_int, rndfile.read(n_bytes))[0] p1 = k * G r = p1.x() if r == 0: raise RuntimeError("amazingly unlucky random number r") s = ( pycoin.ecdsa.numbertheory.inverse_mod( k, n ) * \ ( val + ( secret_exponent * r ) % n ) ) % n if s == 0: raise RuntimeError("amazingly unlucky random number s") return (r, s)
def _build_tbs(csr, days, network): cri = csr.getComponentByName('certificationRequestInfo') subject = cri.getComponentByName('subject') subjectPublicKeyInfo = cri.getComponentByName('subjectPublicKeyInfo') dt_now = datetime.datetime.utcnow() later = datetime.timedelta(days=days) dt_now_str = dt_now.strftime("%y%m%d%H%M%S") + "Z" later_str = (dt_now + later).strftime("%y%m%d%H%M%S") + "Z" notbefore = useful.UTCTime(dt_now_str) notafter = useful.UTCTime(later_str) validity = rfc2459.Validity() validity.setComponentByName('notBefore', notbefore) validity.setComponentByName('notAfter', notafter) tbs = rfc2459.TBSCertificate() tbs.setComponentByName( 'version', rfc2459.Version('v3').subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) rndfile = Random.new() serial = encoding.to_long(256, encoding.byte_to_int, rndfile.read(32))[0] tbs.setComponentByName( 'serialNumber', rfc2459.CertificateSerialNumber(univ.Integer(serial))) tbs.setComponentByName('signature', csr.getComponentByName('signatureAlgorithm')) tbs.setComponentByName('issuer', subject) tbs.setComponentByName('validity', validity) tbs.setComponentByName('subject', subject) tbs.setComponentByName('subjectPublicKeyInfo', subjectPublicKeyInfo) extensionstoadd = "" attributes = cri.getComponentByName('attributes') for attribute in attributes: if (attribute.getComponentByName('type') == utility.OID_PKCShash9ExtensionRequest): value = attribute[1] ## careful with decoder, it returns an implicit type in a tuple extensionstoadd = decoder.decode(value[0])[0] spk = subjectPublicKeyInfo.getComponentByName('subjectPublicKey') ## self siiiigned extensions = _build_extensionsForTbs(extensionstoadd, akipubkeybitstring=spk, skipubkeybitstring=spk) if extensions: tbs.setComponentByName('extensions', extensions) return tbs
def main(): parser = argparse.ArgumentParser( description='utxocsr.py by MiWCryptoCurrency for UTXOC UTXO based certificate signing (to produce PEM encoded).' ) parser.add_argument('-k', '--key', required=True, type=argparse.FileType('r'), help='Private EC Key') parser.add_argument('-c', '--csrfilename', required=True, type=argparse.FileType('r'), help='Input CSR Filename') parser.add_argument('-f', '--certfilename', required=True, type=argparse.FileType('w'), help='Output UTXOC Filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) parser.add_argument('-r', "--redemption", required=False, help='redemption address (to claim after expiry)') parser.add_argument('-d', "--days", required=False, help='number of days to hold Bond (certificate validity period). Suggested >365') inputkey="" inputcsr="" args = parser.parse_args() network = args.network days = 365 if args.days: days = args.days csrfilename = args.csrfilename while True: line = args.key.readline().strip() if not line: break inputkey+= line + '\n' parsed_key = decoder.decode(utility.read_ec_private_pem(inputkey), asn1Spec=utility.ECPrivateKey()) secret_exponent = encoding.to_long(256, encoding.byte_to_int, parsed_key[0][1].asOctets())[0] #coin = Key(secret_exponent=secret_exponent, netcode=network) #pubaddr = coin.address(use_uncompressed=False) while True: line = args.csrfilename.readline().strip() if not line: break inputcsr+= line + '\n' parsed_csr = decoder.decode(utility.read_csr_pem(inputcsr), asn1Spec=rfc2314.CertificationRequest()) tbs = _build_tbs(parsed_csr[0], days, network) certificate = rfc2459.Certificate() certificate.setComponentByName('tbsCertificate', tbs) certificate.setComponentByName('signatureAlgorithm', _build_ECDSAwithSHA256_signatureAlgorithm()) certificate.setComponentByName('signatureValue', _build_signature(parsed_key, tbs, network)) certder = encoder.encode(certificate) certpem = utility.generate_certificate_pem(certder) args.certfilename.write(certpem) print certpem return
def _build_tbs(csr, days, network): cri = csr.getComponentByName('certificationRequestInfo') subject = cri.getComponentByName('subject') subjectPublicKeyInfo = cri.getComponentByName('subjectPublicKeyInfo') dt_now = datetime.datetime.utcnow() later = datetime.timedelta(days=days) dt_now_str = dt_now.strftime("%y%m%d%H%M%S") + "Z" later_str = (dt_now + later).strftime("%y%m%d%H%M%S") + "Z" notbefore = useful.UTCTime(dt_now_str) notafter = useful.UTCTime(later_str) validity = rfc2459.Validity() validity.setComponentByName('notBefore', notbefore) validity.setComponentByName('notAfter', notafter) tbs = rfc2459.TBSCertificate() tbs.setComponentByName('version', rfc2459.Version('v3').subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) rndfile = Random.new() serial = encoding.to_long(256, encoding.byte_to_int, rndfile.read(32))[0] tbs.setComponentByName('serialNumber', rfc2459.CertificateSerialNumber(univ.Integer(serial))) tbs.setComponentByName('signature', csr.getComponentByName('signatureAlgorithm')) tbs.setComponentByName('issuer', subject) tbs.setComponentByName('validity', validity) tbs.setComponentByName('subject', subject) tbs.setComponentByName('subjectPublicKeyInfo', subjectPublicKeyInfo) extensionstoadd = "" attributes = cri.getComponentByName('attributes') for attribute in attributes: if (attribute.getComponentByName('type') == utility.OID_PKCShash9ExtensionRequest): value = attribute[1] ## careful with decoder, it returns an implicit type in a tuple extensionstoadd = decoder.decode(value[0])[0] spk = subjectPublicKeyInfo.getComponentByName('subjectPublicKey') ## self siiiigned extensions = _build_extensionsForTbs(extensionstoadd, akipubkeybitstring=spk, skipubkeybitstring=spk) if extensions: tbs.setComponentByName('extensions', extensions) return tbs
def main(): parser = argparse.ArgumentParser( description= 'utxocsr.py by MiWCryptoCurrency for UTXOC UTXO based certificate signing (to produce PEM encoded).' ) parser.add_argument('-k', '--key', required=True, type=argparse.FileType('r'), help='Private EC Key') parser.add_argument('-c', '--csrfilename', required=True, type=argparse.FileType('r'), help='Input CSR Filename') parser.add_argument('-f', '--certfilename', required=True, type=argparse.FileType('w'), help='Output UTXOC Filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) parser.add_argument('-r', "--redemption", required=False, help='redemption address (to claim after expiry)') parser.add_argument( '-d', "--days", required=False, help= 'number of days to hold Bond (certificate validity period). Suggested >365' ) inputkey = "" inputcsr = "" args = parser.parse_args() network = args.network days = 365 if args.days: days = args.days csrfilename = args.csrfilename while True: line = args.key.readline().strip() if not line: break inputkey += line + '\n' parsed_key = decoder.decode(utility.read_ec_private_pem(inputkey), asn1Spec=utility.ECPrivateKey()) secret_exponent = encoding.to_long(256, encoding.byte_to_int, parsed_key[0][1].asOctets())[0] #coin = Key(secret_exponent=secret_exponent, netcode=network) #pubaddr = coin.address(use_uncompressed=False) while True: line = args.csrfilename.readline().strip() if not line: break inputcsr += line + '\n' parsed_csr = decoder.decode(utility.read_csr_pem(inputcsr), asn1Spec=rfc2314.CertificationRequest()) tbs = _build_tbs(parsed_csr[0], days, network) certificate = rfc2459.Certificate() certificate.setComponentByName('tbsCertificate', tbs) certificate.setComponentByName('signatureAlgorithm', _build_ECDSAwithSHA256_signatureAlgorithm()) certificate.setComponentByName('signatureValue', _build_signature(parsed_key, tbs, network)) certder = encoder.encode(certificate) certpem = utility.generate_certificate_pem(certder) args.certfilename.write(certpem) print certpem return
def do_test(as_int, prefix, as_rep, base): self.assertEqual((as_int, prefix), encoding.to_long(base, encoding.byte_to_int, as_rep)) self.assertEqual(as_rep, encoding.from_long(as_int, prefix, base, lambda v:v))
def do_test(as_int, prefix, as_rep, base): self.assertEqual((as_int, prefix), encoding.to_long(base, encoding.byte_to_int, as_rep)) self.assertEqual( as_rep, encoding.from_long(as_int, prefix, base, lambda v: v))
def main(): parser = argparse.ArgumentParser( description='utxocsr.py by MiWCryptoCurrency for UTXOC UTXO based certificate signing request generation (CSR).' ) parser.add_argument('-k', '--key', required=True, type=argparse.FileType('r'), help='Private EC Key') parser.add_argument('-f', '--filename', required=True, help='Output CSR Filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) parser.add_argument('-t', "--transactionid", required=False, help='transaction id (hex)') inputkey="" args = parser.parse_args() out = args.filename network = args.network while True: line = args.key.readline().strip() if not line: break inputkey += line + '\n' parsed_key = decoder.decode(utility.read_ec_private_pem(inputkey), asn1Spec=utility.ECPrivateKey()) secret_exponent = encoding.to_long(256, encoding.byte_to_int, parsed_key[0][1].asOctets())[0] coin = Key(secret_exponent=secret_exponent, netcode=network) pubaddr = coin.address(use_uncompressed=False) if (network=="BTC"): uriname = "bitcoin" elif (network=="NMC"): uriname = "namecoin" elif (network=="LTC"): uriname = "litecoin" elif (network=="DOGE"): uriname = "dogecoin" elif (network=="BLK"): uriname = "blackcoin" if not args.transactionid: print "Please enter transaction hash to reference in certificate. Leave blank to only encode the address." transactionid = raw_input() if transactionid == "": uri = uriname + ":" + pubaddr else: uri = uriname + ":" + pubaddr + "?" + "transaction=" + transactionid else: transactionid = args.transactionid uri = uriname + ":" + pubaddr + "?" + "transaction=" + transactionid dn = "" dn_c = raw_input("Please enter Country (eg: US): ") if (dn_c == ""): dn_c = "US" dn_st = raw_input("Please enter State (eg: California): ") if (dn_st == ""): dn_st = "California" dn_l = raw_input("Please enter City (eg: Sunnyvale): ") if (dn_l == ""): dn_l = "Sunnyvale" dn_o = raw_input("Please enter Organization (eg: Widgets Inc.): ") if (dn_o == ""): dn_o = "Widgets Inc." dn_ou = raw_input("Please enter Organization Unit: (eg: Information Security): ") if (dn_ou == ""): dn_ou = "Information Security" dn_cn = raw_input("Please enter Common Name: (eg: My first UTXOC): ") if (dn_cn == ""): dn_cn = "My first UTXOC" san = raw_input("Please enter Subject Alt Name values (DNS name, blank for none, seperate multiple entries with space): ") sanentry = [] if (san == ""): sanentry = 'URI:%s' % uri else: for entry in san.split(" "): sanentry.append('DNS:%s' % entry) sanentry.append('URI:%s' % uri) dn = "/C=" + dn_c + "/ST=" + dn_st + "/L=" + dn_l + "/O=" + dn_o + "/OU=" + dn_ou + "/CN=" + dn_cn attributes={ 'extensionRequest': ( ('x509basicConstraints', True, (False,)), ('subjectAlternativeName', False, sanentry ), ) } create_csr_ec(parsed_key, dn, csrfilename=out, attributes=attributes, network=network)
def num_from_bytes(bytes_len, v): # copied from pycoin.encoding.to_bytes_32 if len(v) != bytes_len: raise ValueError("input to num_from_bytes is wrong length") return to_long(256, byte_to_int, v)[0]
def main(): parser = argparse.ArgumentParser( description='verifyutxoc.py by MiWCryptoCurrency for UTXOC UTXO based certificate verify' ) parser.add_argument('-f', '--filename', required=True, type=argparse.FileType('r'), help='Input UTXOC Filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) args = parser.parse_args() network = args.network inputcert = "" while True: line = args.filename.readline() if not line: break inputcert += line parsedcert = None try: parsedcert = decoder.decode(read_pem(inputcert), ECCertificate() )[0] except: print "Problem parsing certificate. Is input x509 Elliptic Curve certificate?" return ############################### ## Check 1 - Is the current date and time within the validity period of the certificate? print "-- Check 1: Date validity--" tbs = parsedcert.getComponentByName("tbsCertificate") validity = tbs.getComponentByName("validity") validityperiod = (validity.getComponentByName("notBefore")[0], validity.getComponentByName("notAfter")[0]) dt_now = datetime.datetime.utcnow() notbefore = str(validityperiod[0][:12]) notafter = str(validityperiod[1][:12]) ## this should work for UTCtime, GeneralTime is YYYY so fix this near the year 2050 dt_notbefore = datetime.datetime(2000 + int(notbefore[0:2]), int(notbefore[2:4]), int(notbefore[4:6]), int(notbefore[6:8]), int(notbefore[8:10]), int(notbefore[10:12])) dt_notafter = datetime.datetime(2000 + int(notafter[0:2]), int(notafter[2:4]), int(notafter[4:6]), int(notafter[6:8]), int(notafter[8:10]), int(notafter[10:12])) timetoexpire = dt_notafter - dt_now if ( dt_now < dt_notbefore ): print "This certificate is not yet valid. Please wait until validity period has started in %s" % timetoexpire return elif ( dt_now > dt_notafter ): print "This certificate has expired %s ago. Please claim any unspent transactions and migrate value to another address" % timetoexpire return print "Certificate will expire on: %s, which is in %s" % (dt_notafter, timetoexpire) print "The date notBefore and notAfter validity checks passed. OK!" ############################### ## Check 2 -- is the public key valid to be used in cryptocurrency? does it match the coin address generated from the public key? print "-- Check 2: Public Key --" print "--- Check 2.1 : Public Key over secp256k1 ---" subjectpublickeyinfo = tbs.getComponentByName("subjectPublicKeyInfo") if checkCurveSecp256k1(subjectpublickeyinfo): print "Certificate contains EC public key over curve secp256k1 OK!" else: return public_pair = subjectPublicKeyInfoToPublicPair(subjectpublickeyinfo) if not public_pair: print "Problem with getting public pair from certificate :-(" return print "Public Key is point (%d %d) on curve secp256k1" % public_pair print "--- Check 2.2 Comparing coin address in SAN to public key in cert ----" extentions = tbs.getComponentByName('extensions') ## the tx should be in the extensions somewhere. ## we also work out the netcode for pycoin here ## currently the last SAN with a coin address will win ## as multiple URI for cointype is not supported at this stage txid = None netcode = None for extension in extentions: oid = extension.getComponentByName('extnID') if (oid != OID_san): continue value = decoder.decode(extension.getComponentByName('extnValue'), asn1Spec=univ.OctetString())[0] sans = decoder.decode(value, asn1Spec=rfc2459.SubjectAltName())[0] for san in sans: santype = san.getName() if santype == 'dNSName': print "Cert is for DNS name: %s" % san.getComponent() elif santype == 'uniformResourceIdentifier': sanuri = san.getComponent().asOctets() if sanuri.startswith('bitcoin:'): netcode = 'BTC' coinuri = sanuri[8:].split('?') coinaddress = coinuri[0] coinparams = coinuri[1].split('&') for coinparam in coinparams: if coinparam.startswith("transaction="): txid = coinparam.split('=')[1] elif sanuri.startswith('dogecoin:'): netcode = 'DOGE' coinuri = sanuri[9:].split('?') coinaddress = coinuri[0] coinparams = coinuri[1].split('&') for coinparam in coinparams: if coinparam.startswith("transaction="): txid = coinparam.split('=')[1] elif sanuri.startswith('litecoin:'): netcode = 'LTC' coinuri = sanuri[9:].split('?') coinaddress = coinuri[0] coinparams = coinuri[1].split('&') for coinparam in coinparams: if coinparam.startswith("transaction="): txid = coinparam.split('=')[1] elif sanuri.startswith('blackcoin:'): netcode = 'BLK' coinuri = sanuri[10:].split('?') coinaddress = coinuri[0] coinparams = coinuri[1].split('&') for coinparam in coinparams: if coinparam.startswith("transaction="): txid = coinparam.split('=')[1] if not txid: print "No Coin address or TX found in SubjectAltName. Cannot be a UTXOC :-(" return print "Found Coin Address: %s and Transaction: %s" % (coinaddress, txid) pycoin_key = pycoin.key.Key(public_pair=public_pair, netcode=netcode) if not (coinaddress == pycoin_key.address() ): print "Coin address does not match public key on certificate! :-(" return print "Address matches subject public key. OK!" ############################### ## Is our transaction unspent? Using blockchain.info API and chain.so data API to validate Unspent. print "-- Check 3: Is the transaction unspent? --" utxo_valid = False ## dont forget to check the txid just in case its something malicious smuggled in through the cert and passed to requests ## its a SHA-256 hash so its 64 chracters if not (len(txid) == 64): print "TXID wrong size, is not a SHA-256 Hash" return ## try convert from hex, catches bad characters try: int(txid, 16) except: print "illegal characters, cannot be a SHA-256 Hash" return ## use blockchain.info for BTC ## use chain.so for DOGE ## use ??? for BLK ## use ??? for NMC if (netcode=='BTC'): if checkBlockchainInfoUTXO(coinaddress, txid) and checkChainSoUTXO(netcode, coinaddress, txid): utxo_valid = True elif (netcode=='DOGE') or (netcode=='LTC'): utxo_valid = checkChainSoUTXO(netcode, coinaddress, txid) else: print "Unsupported coin %s for 3rd party chain lookup" % netcode return # did we get a valid utxo confirmed by 3rd party? if utxo_valid: print "UTXO valid! OK!" else: print "UTXO invalid! :-(" return ############################### ## Check 4 - Signature: If self-signed or issuer signed? Check that signature against trusted signer list print "-- Check 4: Signature --" ## check the issuer attrib certissuer = tbs.getComponentByName('issuer') print "UTXOC is Signed by: %s" % subjectDnToString(certissuer) certsubject = tbs.getComponentByName('subject') if (certissuer == certsubject): print "Self Signed Cert: CA or 'bond' style UTXOC" signer_public_pair = public_pair else: build_trusted_signer_list() signer_public_pair = trusted_signer_list[subjectDnToString(certissuer)] if not signer_public_pair: print "Signing Cert not found in trusted signer store" return certsigalgo = parsedcert.getComponentByName('signatureAlgorithm') certsigvalue = parsedcert.getComponentByName('signatureValue') rawsig = bitStringtoOctetString(certsigvalue) sigder = "" for hchar in rawsig: sigder+=hchar sig_pair = decoder.decode(sigder)[0] if not (certsigalgo[0] == OID_ecdsaWithSHA256): print "Certificate not signed with ecdsa-SHA256" return r = long(sig_pair[0]) s = long(sig_pair[1]) # generate digest of the tbs tbsder = encoder.encode(tbs) hashvalue = SHA256.new(tbsder) hexdgst = hashvalue.hexdigest() dgst = hashvalue.digest() dgstaslong = encoding.to_long(256, encoding.byte_to_int, dgst)[0] # if pycoin.ecdsa.verify(generator_secp256k1, signer_public_pair, dgstaslong, (r,s)): print "Signature validated. OK!" else: print "Signature validation failed!" return print "------------------------------ ALL TESTS PASSED ------------------------------" return
def main(): parser = argparse.ArgumentParser( description= 'utxocsr.py by MiWCryptoCurrency for UTXOC UTXO based certificate signing request generation (CSR).' ) parser.add_argument('-k', '--key', required=True, type=argparse.FileType('r'), help='Private EC Key') parser.add_argument('-f', '--filename', required=True, help='Output CSR Filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) parser.add_argument('-t', "--transactionid", required=False, help='transaction id (hex)') inputkey = "" args = parser.parse_args() out = args.filename network = args.network while True: line = args.key.readline().strip() if not line: break inputkey += line + '\n' parsed_key = decoder.decode(utility.read_ec_private_pem(inputkey), asn1Spec=utility.ECPrivateKey()) secret_exponent = encoding.to_long(256, encoding.byte_to_int, parsed_key[0][1].asOctets())[0] coin = Key(secret_exponent=secret_exponent, netcode=network) pubaddr = coin.address(use_uncompressed=False) if (network == "BTC"): uriname = "bitcoin" elif (network == "NMC"): uriname = "namecoin" elif (network == "LTC"): uriname = "litecoin" elif (network == "DOGE"): uriname = "dogecoin" elif (network == "BLK"): uriname = "blackcoin" if not args.transactionid: print "Please enter transaction hash to reference in certificate. Leave blank to only encode the address." transactionid = raw_input() if transactionid == "": uri = uriname + ":" + pubaddr else: uri = uriname + ":" + pubaddr + "?" + "transaction=" + transactionid else: transactionid = args.transactionid uri = uriname + ":" + pubaddr + "?" + "transaction=" + transactionid dn = "" dn_c = raw_input("Please enter Country (eg: US): ") if (dn_c == ""): dn_c = "US" dn_st = raw_input("Please enter State (eg: California): ") if (dn_st == ""): dn_st = "California" dn_l = raw_input("Please enter City (eg: Sunnyvale): ") if (dn_l == ""): dn_l = "Sunnyvale" dn_o = raw_input("Please enter Organization (eg: Widgets Inc.): ") if (dn_o == ""): dn_o = "Widgets Inc." dn_ou = raw_input( "Please enter Organization Unit: (eg: Information Security): ") if (dn_ou == ""): dn_ou = "Information Security" dn_cn = raw_input("Please enter Common Name: (eg: My first UTXOC): ") if (dn_cn == ""): dn_cn = "My first UTXOC" san = raw_input( "Please enter Subject Alt Name values (DNS name, blank for none, seperate multiple entries with space): " ) sanentry = [] if (san == ""): sanentry = 'URI:%s' % uri else: for entry in san.split(" "): sanentry.append('DNS:%s' % entry) sanentry.append('URI:%s' % uri) dn = "/C=" + dn_c + "/ST=" + dn_st + "/L=" + dn_l + "/O=" + dn_o + "/OU=" + dn_ou + "/CN=" + dn_cn attributes = { 'extensionRequest': ( ('x509basicConstraints', True, (False, )), ('subjectAlternativeName', False, sanentry), ) } create_csr_ec(parsed_key, dn, csrfilename=out, attributes=attributes, network=network)
def main(): parser = argparse.ArgumentParser( description='ECkey2coin.py by [email protected] for UTXO based Certificates UTXOC.', epilog='Known networks codes:\n ' \ + ', '.join(['%s (%s)'%(i, full_network_name_for_netcode(i)) for i in NETWORK_NAMES]) ) parser.add_argument('-k', '--key', required=False, type=argparse.FileType('r'), help='The EC private key in PEM format') parser.add_argument('-q', '--qrfilename', required=False, help='QR code output filename') parser.add_argument('-n', "--network", help='specify network (default: BTC = Bitcoin)', default='BTC', choices=NETWORK_NAMES) args = parser.parse_args() network = args.network inputprivatekey = '' if args.key: keyfile = args.key while True: line = keyfile.readline().strip() if not line: break inputprivatekey += line + '\n' print 'Loaded EC Key from %s' % keyfile else: print ('Please enter EC KEY in pem format:') inputprivatekey = '' while True: line = raw_input().strip() if not line: break inputprivatekey += line + '\n' if not args.qrfilename: qrfilename = raw_input("Please enter qrcode output filename: ") else: qrfilename = args.qrfilename pkey = decoder.decode(read_pem(inputprivatekey), asn1Spec=ECPrivateKey()) print 'Key loaded' if not isValidECKey(pkey[0]): print "EC Key Supplied cannot be used" exit print "Key Validated OK" inputkey = encoding.to_long(256, pycoin.encoding.byte_to_int, pkey[0][1].asOctets())[0] if inputkey: key = Key(secret_exponent=inputkey, netcode=network) btcsecret = key.secret_exponent() btcpublic = key.public_pair() hash160_c = key.hash160(use_uncompressed=False) hash160_u = key.hash160(use_uncompressed=True) qrimg = qrcode.QRCode ( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qrimg.add_data(key.address(use_uncompressed=False)) qrimg.make(fit=True) img = qrimg.make_image() img.save(qrfilename) print"----------------- BEGIN EC PRIVATE KEYS -----------------" print "Secret: %d" % btcsecret print "Secret hex: %x" % btcsecret print "wif: %s" % key.wif(use_uncompressed=False) print "----------------- END EC PRIVATE KEYS -----------------------------" print "----------------- BEGIN PUBLIC KEY -----------------------------" print "Public X: %d" % btcpublic[0] print "Public Y: %d" % btcpublic[1] print "hash160 uncompressed: %s" % b2h(hash160_u) print "Sec: (uncompressed): %s" % b2h(key.sec(use_uncompressed=True)) print "%s address: %s (uncompressed)" % (key._netcode, key.address(use_uncompressed=True)) print "Public X (hex): %x" % btcpublic[0] print "Public Y (hex): %x" % btcpublic[1] print "Sec: %s" % b2h(key.sec(use_uncompressed=False)) print "hash160 compressed: %s" % b2h(hash160_c) print "----------------- END PUBLIC KEYS -----------------------------" print "------------------ BEGIN %s ADDRESSES -------------------------" % key._netcode print "%s address: %s" % (key._netcode, key.address(use_uncompressed=False)) print "------------------ END %s ADDRESSES -------------------------" % key._netcode