def test_domain1(self): """Verify we can generate new keys in a given domain""" dsa_key_1 = DSA.generate(1024) domain_params = dsa_key_1.domain() dsa_key_2 = DSA.generate(1024, domain=domain_params) self.assertEqual(dsa_key_1.p, dsa_key_2.p) self.assertEqual(dsa_key_1.q, dsa_key_2.q) self.assertEqual(dsa_key_1.g, dsa_key_2.g) self.assertEqual(dsa_key_1.domain(), dsa_key_2.domain())
def test_domain1(self): """Verify we can generate new keys in a given domain""" dsa_key_1 = DSA.generate(1024) domain_params = dsa_key_1.domain() dsa_key_2 = DSA.generate(1024, domain=domain_params) self.assertEqual(dsa_key_1.p, dsa_key_2.p) self.assertEqual(dsa_key_1.q, dsa_key_2.q) self.assertEqual(dsa_key_1.g, dsa_key_2.g) self.assertEqual(dsa_key_1.domain(), dsa_key_2.domain())
def crypto(): from Crypto.PublicKey import DSA, RSA # bits = DSA key size DSA.generate(bits=1024) # Noncompliant DSA.generate(bits=2048) # Compliant # bits = RSA key size # e = RSA public key exponent RSA.generate(bits=1024, e=65537) # Noncompliant RSA.generate(e=65537, bits=1024) # Noncompliant RSA.generate(bits=2048, e=999) # Noncompliant RSA.generate(bits=2048, e=65537) # Compliant RSA.generate(2048, None, None, 999) # Noncompliant
def DSA_keyGen(client): # Create a new DSA key key = DSA.generate(2048) f = open(client + "_DSA_public_key.pem", "wb") f.write(key.publickey().exportKey()) f.close() return key
def baby_proof(): key = DSA.generate(3072) # It takes time to generate, plz be patient... p, q, g = key.domain() y = pow(g, x, p) v = getRandomRange(1, x) t = pow(g, v, p) gyt = b"".join( map(lambda x: int.to_bytes(len(str(x)), 4, 'big') + str(x).encode(), (g, y, t))) c = int.from_bytes(sha256(gyt).digest(), 'big') r = (v - c * x) % q print("I want to prove to you that I am in the knowledge of the discrete " "logarithm x that satisfies g^x = y modulo p, with the order of g " "modulo p being q.") print("However, I don't want to leak any information about x.") print("So, I use a non-interactive zero-knowledge proof for my purpose.") print("=================================================================") print("Here is my proof: ") print("Firstly, I choose a random (secret) v and compute t = g^v in Zq.") print("Secondly, I compute c = SHA256(g, y, t).") print("Then, I compute r = v - cx modulo q.") print("Finally, I will send you my proof (t, r).") print("You can check it by determining whether t == g^r * y^c or not.") print("Since there's negligible probability that I could forge the value " "r, you should believe that I really have knowledge of x.") print(g, y, p, q, t, r, sep="\n")
def test_nonce_reuse(secret_key=DSA.generate(1024)): # choose a "random" - k :) this time random is static in order to allow this attack to work k = random.StrongRandom().randint(1, secret_key.q - 1) # sign two messages using the same k samples = (Tests.Dsa.signMessage(secret_key, "This is a signed message!", k), Tests.Dsa.signMessage(secret_key, "Another signed Message - :)", k)) logger.debug("generated sample signatures: %s" % repr(samples)) signatures = [ DsaSignature(sig, h, pubkey) for h, sig, pubkey in samples ] logger.debug("Signature Objects: %r" % signatures) two_sigs = [] for sig in signatures: two_sigs.append(sig) if not len(two_sigs) == 2: continue sample = two_sigs.pop(0) logger.debug("%r - recovering privatekey from nonce reuse..." % sample) assert (sample.x is None) # not yet resolved sample.recover_nonce_reuse(two_sigs[0]) assert (sample.x is not None) # privkey recovered assert (sample.privkey == secret_key) logger.debug("%r - Private key recovered! \n%s" % (sample, sample.export_key()))
def DSA_1024(data): times = [] key = DSA.generate(1024) h = SHA512.new(data) controler = DSS.new(key, 'fips-186-3') start = time.clock() signature = controler.sign(h) end = time.clock() print(signature.hex()) times.append(end - start) try: start = time.clock() controler.verify(h, signature) end = time.clock() print('The message is authentic') except ValueError: print('The message is not authentic') times.append(end - start) return times
def __init__(self, obf=False): self.dsakey = DSA.generate(1024) #, randfunc=wrandom) self.rndv = [ random.randint(1000000000, self.dsakey.q - 1000000000) for _ in range(GRND) ] self.obf = obf
def exec_dsa(form): other_params = {} message = form.text.data.encode("utf-8") hash_ = SHA.new(message) form.sha.data = hash_.hexdigest() h = hash_.digest() # 恢复key if not session.get("key"): key = DSA.generate(1024) session["key"] = pickle.dumps(key) else: key = pickle.loads(session["key"]) if form.sign.data: k = random.StrongRandom().randint(1, key.q - 1) sig = key.sign(h, k) form.signature.data = "%s, %s" % (hex(sig[0])[2:-1], hex(sig[1])[2:-1]) elif form.verify.data: ssig = form.signature.data.split(", ") try: sig = (int(ssig[0], base=16), int(ssig[1], base=16)) except (IndexError, UnicodeEncodeError): flash(u"签名格式错误!") else: if key.verify(h, sig): flash(u"签名验证成功!") else: flash(u"签名验证失败!") return form, other_params
def DSS_sign(message): key = DSA.generate(2048) publickey = key.publickey() hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) print(hash_obj.hexdigest())
def __init__(self): """ Constructs the DSAExample object. """ self.key = DSA.generate(2048) self.signer = DSS.new(self.key, 'fips-186-3') self.verifier = DSS.new(self.key, 'fips-186-3')
def encrypt(self): """ Takes in user message and generates random public key in file public_key.pem. Based on those things creates digital signature in signature.txt file. Parameters ---------- self : String User-specified input plain text message Returns ------- "Saved signature: " + str(signature) + " to signature.txt file." : String Information about saved digital signature in signature.txt """ key = DSA.generate(2048) f = open("public_key.pem", "wb") f.write(key.publickey().export_key()) f.close() message = self.encode() hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) fs = open("signature.txt", "wb") fs.write(signature) fs.close() return "Saved signature: " + str(signature) + " to signature.txt file."
def exec_dsa(form): other_params = {} message = form.text.data.encode("utf-8") hash_ = SHA.new(message) form.sha.data = hash_.hexdigest() h = hash_.digest() # 恢复key if not session.get("key"): key = DSA.generate(1024) session["key"] = pickle.dumps(key) else: key = pickle.loads(session["key"]) if form.sign.data: k = random.StrongRandom().randint(1,key.q-1) sig = key.sign(h, k) form.signature.data = "%s, %s"%(hex(sig[0])[2:-1], hex(sig[1])[2:-1]) elif form.verify.data: ssig = form.signature.data.split(", ") try: sig = (int(ssig[0], base=16), int(ssig[1], base=16)) except (IndexError, UnicodeEncodeError): flash(u"签名格式错误!") else: if key.verify(h, sig): flash(u"签名验证成功!") else: flash(u"签名验证失败!") return form, other_params
def genKeys(bits): key = DSA.generate(1024) seq = asn1.DerSequence() seq[:] = [0, key.p, key.q, key.g, key.y, key.x] k2 = "-----BEGIN DSA PRIVATE KEY-----\n%s-----END DSA PRIVATE KEY-----" % seq.encode( ).encode("base64") return k2
def __init__(self, scrooge: Scrooge): # generate private/public key pair self.key = DSA.generate(1024) self.scrooge = scrooge self.coins = {} # Only for the purpose of simulating double spending self.double_spending_coins = {} self.id = User.gen_id()
def test_dsa_private_key(self): key = DSA.generate(2048) private_key_encoded = base64.b64encode( key.export_key()).decode('utf-8') protected_settings = _get_protected_settings(private_key_encoded, '', '', '') self.assertEqual('sshPrivateKey' in protected_settings, True) self.assertEqual(protected_settings.get('sshPrivateKey'), private_key_encoded)
def __init__(self,file=None,Rec=None,List=None,Size=512): if file: self.dsa = DSA.construct(cPickle.load(open(file, 'rb'))) elif Rec: self.unpack(Rec) elif List: self.dsa = DSA.construct(List) else: self.dsa = DSA.generate(Size, HIPutils.RandomPool.get_bytes)
def private_key_generate(): key = DSA.generate(1024) y = str(key.y) g = str(key.g) p = str(key.p) q = str(key.q) x = str(key.x) next_id = get_next_id('d_private_key') return [y, g, p, q, x], next_id
def generate_asymmetric(self, generate_dto, kek_meta_dto, project_id): """Generate asymmetric keys based on below rules: - RSA, with passphrase (supported) - RSA, without passphrase (supported) - DSA, without passphrase (supported) - DSA, with passphrase (not supported) Note: PyCrypto is not capable of serializing DSA keys and DER formated keys. Such keys will be serialized to Base64 PEM to store in DB. TODO (atiwari/reaperhulk): PyCrypto is not capable to serialize DSA keys and DER formated keys, later we need to pick better crypto lib. """ if(generate_dto.algorithm is None or generate_dto .algorithm.lower() == 'rsa'): private_key = RSA.generate( generate_dto.bit_length, None, None, 65537) elif generate_dto.algorithm.lower() == 'dsa': private_key = DSA.generate(generate_dto.bit_length, None, None) else: raise c.CryptoPrivateKeyFailureException() public_key = private_key.publickey() # Note (atiwari): key wrapping format PEM only supported if generate_dto.algorithm.lower() == 'rsa': public_key, private_key = self._wrap_key(public_key, private_key, generate_dto.passphrase) if generate_dto.algorithm.lower() == 'dsa': if generate_dto.passphrase: raise ValueError(u._('Passphrase not supported for DSA key')) public_key, private_key = self._serialize_dsa_key(public_key, private_key) private_dto = self.encrypt(c.EncryptDTO(private_key), kek_meta_dto, project_id) public_dto = self.encrypt(c.EncryptDTO(public_key), kek_meta_dto, project_id) passphrase_dto = None if generate_dto.passphrase: if isinstance(generate_dto.passphrase, six.text_type): generate_dto.passphrase = generate_dto.passphrase.encode( 'utf-8') passphrase_dto = self.encrypt(c.EncryptDTO(generate_dto. passphrase), kek_meta_dto, project_id) return private_dto, public_dto, passphrase_dto
def dsa_reg(usr, name, sex_zh, unit, title): # Database connection conn = MySQLdb.connect(host='localhost', user='******', passwd='123456', db='project', charset='utf8') cur = conn.cursor() # Gender transfer if sex_zh == u'男': sex = 0 elif sex_zh == u'女': sex = 1 # Unit transfer sql_unit = "SELECT * FROM unit WHERE unit_name = '%s'" % unit cur.execute(sql_unit) result_unit = cur.fetchall() unitid = result_unit[0][0] # Avoid duplication sql_search = "SELECT * FROM users WHERE loginid = '%s'" % usr if cur.execute(sql_search) == 0L: # Insert into database sql = "insert into users(loginid, pass_word, name, sex, unitid, title) values('%s', '', '%s', '%d', '%d', '%s')" % ( usr, name, sex, unitid, title) cur.execute(sql) conn.commit() cur.close() conn.close() # Key generation key = DSA.generate(1024) # Key data y = key.y g = key.g p = key.p q = key.q x = key.x # Save user's public key f = open('auth/dsa/keys/%s.pub' % usr, 'w') f.write(str(y) + ' ' + str(g) + ' ' + str(p) + ' ' + str(q)) f.close() return 1, y, g, p, q, x # Registeration failed else: return 2, 0, 0, 0, 0, 0
def Question_G_and_H(keysize): kb = open('1kb.bin', 'rb') Mb = open('1Mb.bin', 'rb') kb_cont = kb.read() Mb_cont = Mb.read() a = timeit.default_timer() key = DSA.generate(keysize) b = timeit.default_timer() publickey = key.publickey() hash_obj = SHA256.new(kb_cont) signer = DSS.new(key, 'fips-186-3') c = timeit.default_timer() signature = signer.sign(hash_obj) d = timeit.default_timer() pkey = DSS.new(publickey, 'fips-186-3') try: e = timeit.default_timer() pkey.verify(hash_obj, signature) f = timeit.default_timer() valid = True except ValueError: valid = False print(valid) hash_obj = SHA256.new(Mb_cont) signer = DSS.new(key, 'fips-186-3') g = timeit.default_timer() signature = signer.sign(hash_obj) h = timeit.default_timer() pkey = DSS.new(publickey, 'fips-186-3') try: i = timeit.default_timer() pkey.verify(hash_obj, signature) j = timeit.default_timer() valid = True except ValueError: valid = False print(valid) print() print("Key generation time:", b - a) print("Time to produce a signature for 1kb file:", d - c) print("Time to produce a signature for 1Mb file:", h - g) print("Time to verify a signature for 1kb file:", f - e) print("Time to verify a signature for 1Mb file:", j - i) print() print("Signature producing speed for 1kb file:", (d - c) / 1024) print("Signature producing speed for 1Mb file:", (h - g) / 1024000) print("Signature verifying speed for 1kb file:", (f - e) / 1024) print("Signature verifying speed for 1Mb file:", (j - i) / 1024000)
def __init__(self, relayPort, password): """Init.""" myDSAKeys = DSA.generate(1024) self.myDSAPublicKey = myDSAKeys.publickey() self.encryptedDSAKey = CryptoLib.encryptWalletDSAKey(password, myDSAKeys) self.address = CryptoLib.getAddressFromPublicKey(self.myDSAPublicKey.y) self.unspentTxs = [] self.relayPort = relayPort self.relayIP = "http://localhost:" + str(self.relayPort) self.BlockChain = []
def generate_DSA_agentkey(): key = DSA.generate(1024) agent_pubkey_epo_format = b'\x01\x00\x0c\x00' \ + b'agpubkey.bin' \ + b'\x9c\x01\x00\x00' \ + b'\x40\x00' + key.p.to_bytes(128, 'little') \ + b'\x00\xa0' + key.q.to_bytes(20, 'little') \ + b'\x03\xff' + key.g.to_bytes(128, 'little') \ + b'\x03\xfc' + key.y.to_bytes(128, 'little') return agent_pubkey_epo_format
def __init__(self, p_length=None, p=None, q=None, g=None): if p == None: dsa = DSA.generate(p_length) self.p = dsa.p self.q = dsa.q self.g = dsa.g else: self.p = p self.q = q self.g = g Z_m.__init__(self, self.p, self.q)
def sign(self, message): # Create a new DSA key key = DSA.generate(1024) # Sign a message message = bytes(message.encode()) hash_obj = SHA256.new(message) signer = DSS.new(key, 'fips-186-3') start_time = timer() signature = signer.sign(hash_obj) self.executionTime = timer() - start_time return signature.hex().upper()
def generate_asymmetric(self, generate_dto, kek_meta_dto, project_id): """Generate asymmetric keys based on below rules: - RSA, with passphrase (supported) - RSA, without passphrase (supported) - DSA, without passphrase (supported) - DSA, with passphrase (not supported) Note: PyCrypto is not capable of serializing DSA keys and DER formated keys. Such keys will be serialized to Base64 PEM to store in DB. TODO (atiwari/reaperhulk): PyCrypto is not capable to serialize DSA keys and DER formated keys, later we need to pick better crypto lib. """ if (generate_dto.algorithm is None or generate_dto.algorithm.lower() == 'rsa'): private_key = RSA.generate(generate_dto.bit_length, None, None, 65537) elif generate_dto.algorithm.lower() == 'dsa': private_key = DSA.generate(generate_dto.bit_length, None, None) else: raise c.CryptoPrivateKeyFailureException() public_key = private_key.publickey() # Note (atiwari): key wrapping format PEM only supported if generate_dto.algorithm.lower() == 'rsa': public_key, private_key = self._wrap_key(public_key, private_key, generate_dto.passphrase) if generate_dto.algorithm.lower() == 'dsa': if generate_dto.passphrase: raise ValueError(u._('Passphrase not supported for DSA key')) public_key, private_key = self._serialize_dsa_key( public_key, private_key) private_dto = self.encrypt(c.EncryptDTO(private_key), kek_meta_dto, project_id) public_dto = self.encrypt(c.EncryptDTO(public_key), kek_meta_dto, project_id) passphrase_dto = None if generate_dto.passphrase: if isinstance(generate_dto.passphrase, six.text_type): generate_dto.passphrase = generate_dto.passphrase.encode( 'utf-8') passphrase_dto = self.encrypt( c.EncryptDTO(generate_dto.passphrase), kek_meta_dto, project_id) return private_dto, public_dto, passphrase_dto
def generateKeys(): random_gen = Random.new().read key = DSA.generate(1024,random_gen) seq = asn1.DerSequence() seq[:] = [ 0, key.p, key.q, key.g, key.y, key.x ] exported_private = "-----BEGIN DSA PRIVATE KEY-----\n%s-----END DSA PRIVATE KEY-----" % seq.encode().encode("base64") key = key.publickey() seq = asn1.DerSequence() seq[:] = [ 0, key.p, key.q, key.g, key.y ] exported_public = "-----BEGIN DSA PUBLIC KEY-----\n%s-----END DSA PUBLIC KEY-----" % seq.encode().encode("base64") keys = [exported_private,exported_public] return keys
def make_DSA_keys(): # generate a pair of private and public DSA keys key = DSA.generate(1024) response = { 'private key': str(key.x), 'public key': str(key.y), 'generator': str(key.g), 'modulus': str(key.p), 'sub-group order': str(key.q) } return jsonify(response), 200
def DSS_sign(c): key = DSA.generate(2048) global public_key public_key = key.publickey() if c == "a": hash_obj = SHA256.new(a_peer_public_key) else: hash_obj = SHA256.new(b_peer_public_key) signer = DSS.new(key, 'fips-186-3') signature = signer.sign(hash_obj) global s s = signer.sign(hash_obj) return hash_obj.hexdigest(), signature
def Simulation(): global file global ListOfTransactions global BlockChain ScroogeKey = DSA.generate(1024) UsersList.append(User("Scrooge", ScroogeKey.publickey(), ScroogeKey, [])) for i in range(25): Key = DSA.generate(1024) UsersList.append(User(str(uuid.uuid1()), Key.publickey(), Key, [])) for i in range(len(UsersList)): p = "User: "******", " + str(UsersList[i].PublicKey) + ", Amount of coins: " + str(len(UsersList[i].Coins)) + "\n" print(p) file.write(p) for i in range(len(UsersList)): if i > 0: F = MakeCoins(UsersList[0].PrivateKey, 10) ListOfTransactions.append(F) for z in range(len(F.ListOfCoins)): UsersList[0].Coins.append(F.ListOfCoins[z]) if len(ListOfTransactions) == 10: ListOfTransactions = VerifyTransaction(ListOfTransactions) SendCoins(10, UsersList[0].ID, UsersList[i].ID, UsersList[0].Coins[len(UsersList[0].Coins) - 10:]) while True: if keyboard.is_pressed('space'): Header = str(BlockChain[len(BlockChain)-1].ID) HashID = SHA256.new(bytes(Header, 'utf-8')) Sign = DSS.new(UsersList[0].PrivateKey, 'fips-186-3') Signature = Sign.sign(HashID) BlockChain[len(BlockChain)-1].HashPointer = Signature p = "\nLast block_ID: " + BlockChain[len(BlockChain)-1].ID + ", Hash of block: " + str(BlockChain[len(BlockChain)-1].Hash) + ", Signature of Scrooge: " + str(BlockChain[len(BlockChain)-1].HashPointer) + "\n" print(p) file.write(p) print("Program Terminated") file.close() break else: RandomTransaction()
def test_dsa_sign(): global key key = DSA.generate(1024) d = get_dsa_key(key) M = "This is a test message, OK?" K = bytes_to_long(os.urandom(19)) + 2 H = SHA256.new(M) signature = key.sign(H.digest(), K) assert key.verify(H.digest(), signature) d["M"] = M d["H"] = H.hexdigest() d["K"] = hex(K)[2:-1] d["Signature"] = [hex(_)[2:-1] for _ in signature] return d
def post(self): args = dsa_key_parser.parse_args() key_size = args["key_size"] key_pair = DSA.generate(key_size) public_key = key_pair.publickey().exportKey("PEM") private_key = key_pair.exportKey("PEM") data = { "public_key": public_key.decode("ascii"), "private_key": private_key.decode("ascii"), } return jsonify(data)
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param function progress_func: an optional function to call at key points in key generation (used by ``pyCrypto.PublicKey``). :return: new `.DSSKey` private key """ dsa = DSA.generate(bits, os.urandom, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
def make_key_objects(pub_algorithm_type, key_size): if pub_algorithm_type == 17: secret_key = DSA.generate(key_size) elif pub_algorithm_type in (1, 3): secret_key = RSA.generate(key_size) elif pub_algorithm_type == 20: # TODO: This should not be allowed except for testing purposes. # XXX: This can take a really long time secret_key = ElGamal.generate(key_size, Random.new().read) else: # TODO: complete raise ValueError public_key = secret_key.publickey() return secret_key, public_key
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param function progress_func: an optional function to call at key points in key generation (used by ``pyCrypto.PublicKey``). :return: new `.DSSKey` private key """ dsa = DSA.generate(bits, os.urandom, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
def main(args): message = "Hello, P2PSP!" * 1024 key = DSA.generate(1024) # measure the sign time start_time = time.time() for _ in xrange(N): sig = sign(message, key) print "key.sign x{0} times: {1}s".format(N, time.time() - start_time) #measure the verify time sig = sign(message, key) start_time = time.time() for _ in xrange(N): r = check(message, key, sig) print "key.verify x{0} times: {1}s".format(N, time.time() - start_time)
def create(password, address_label): if len(bytes( password, ENCODING_UTF8)) != PASSWORD_LENGTH: # Pw must be of 16 bytes return None new_key = DSA.generate(P_SIZE) address = Address() address.private_key = new_key.exportKey() address.public_key = new_key.publickey().exportKey() address.raw = Address.generate_address(address.public_key) if address_label == '': address_label = address.raw address.label = address_label address.save(password) return address
def _generate_dsa_keypair_as_objects(key_length_bits: int) -> dict: """Generate a DSA (public_key, private_key) pair. DSA keypair is not used for encryption/decryption, only for signing. :param key_length_bits: length of the key in bits, must be superior to 2048. :return: dictionary with "private_key" and "public_key" fields as objects.""" _check_asymmetric_key_length_bits(key_length_bits) private_key = DSA.generate(key_length_bits) public_key = private_key.publickey() keypair = {"public_key": public_key, "private_key": private_key} return keypair
def generate_asymmetric(self, generate_dto, kek_meta_dto, keystone_id): """Generate asymmetric keys based on below rule - RSA, with passphrase (supported) - RSA, without passphrase (supported) - DSA, without passphrase (supported) - DSA, with passphrase (not supported) Note: PyCrypto is not capable of serializing DSA keys and DER formated keys. Such keys will be serialized to Base64 PEM to store in DB. TODO (atiwari/reaperhulk): PyCrypto is not capable to serialize DSA keys and DER formated keys, later we need to pick better crypto lib. """ if generate_dto.algorithm is None\ or generate_dto.algorithm.lower() == 'rsa': private_key = RSA.generate( generate_dto.bit_length, None, None, 65537) elif generate_dto.algorithm.lower() == 'dsa': private_key = DSA.generate(generate_dto.bit_length, None, None) public_key = private_key.publickey() # Note (atiwari): key wrapping format PEM only supported if generate_dto.algorithm.lower() == 'rsa': public_key, private_key = self._wrap_key(public_key, private_key, generate_dto.passphrase) if generate_dto.algorithm.lower() == 'dsa': if generate_dto.passphrase: raise ValueError('Passphrase not supported for DSA key') public_key, private_key = self._serialize_dsa_key(public_key, private_key) private_dto = self.encrypt(EncryptDTO(private_key), kek_meta_dto, keystone_id) public_dto = self.encrypt(EncryptDTO(public_key), kek_meta_dto, keystone_id) passphrase_dto = None if generate_dto.passphrase: passphrase_dto = self.encrypt(EncryptDTO(generate_dto.passphrase), kek_meta_dto, keystone_id) return private_dto, public_dto, passphrase_dto
def exportKeys(): random_gen = Random.new().read key = DSA.generate(1024,random_gen) seq = asn1.DerSequence() seq[:] = [0,key.p,key.q,key.g,key.y,key.x] exported_private = "-----BEGIN DSA PRIVATE KEY-----\n%s-----END DSA PRIVATE KEY-----" % seq.encode().encode("base64") pubkey = key.publickey() seq = asn1.DerSequence() seq[:] = [0,pubkey.p,pubkey.q,pubkey.g,pubkey.y] exported_public = "-----BEGIN DSA PUBLIC KEY-----\n%s-----END DSA PUBLIC KEY-----" % seq.encode().encode("base64") file = open("PrivateDSAKey.pem","w") file.write(exported_private) file.close() file = open("PublicDSAKey.pem","w") file.write(exported_public) file.close()
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
def getDSAKeys(): cfg = config() public_key = cfg.get('honeypot', 'dsa_public_key') private_key = cfg.get('honeypot', 'dsa_private_key') if not (os.path.exists(public_key) and os.path.exists(private_key)): print "Generating new DSA keypair..." from Crypto.PublicKey import DSA from twisted.python import randbytes KEY_LENGTH = 1024 dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom) publicKeyString = twisted.conch.ssh.keys.Key(dsaKey).public().toString('openssh') privateKeyString = twisted.conch.ssh.keys.Key(dsaKey).toString('openssh') file(public_key, 'w+b').write(publicKeyString) file(private_key, 'w+b').write(privateKeyString) else: publicKeyString = file(public_key).read() privateKeyString = file(private_key).read() return publicKeyString, privateKeyString
def Generate(size=keyinfo.DSA_PRIV.default_size): """ Return a newly generated DSA private key. @param size: length of key in bits to generate @type size: integer @return: a DSA private key @rtype: L{DsaPrivateKey} """ key = DSA.generate(size, util.RandBytes) params = { 'x': util.BigIntToBytes(key.x)} pubkey = key.publickey() pub_params = { 'g': util.BigIntToBytes(pubkey.g), 'p': util.BigIntToBytes(pubkey.p), 'q': util.BigIntToBytes(pubkey.q), 'y': util.BigIntToBytes(pubkey.y) } pub = DsaPublicKey(pub_params, pubkey, size) return DsaPrivateKey(params, pub, key, size)
def getDSAKeys(): public_key = os.path.join(SSH_PATH, 'id_dsa.pub') private_key = os.path.join(SSH_PATH, 'id_dsa') if not (os.path.exists(public_key) and os.path.exists(private_key)): from Crypto.PublicKey import DSA from twisted.python import randbytes KEY_LENGTH = 1024 dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom) publicKeyString = keys.Key(dsaKey).public().toString('openssh') privateKeyString = keys.Key(dsaKey).toString('openssh') with file(public_key, 'w+b') as f: f.write(publicKeyString) with file(private_key, 'w+b') as f: f.write(privateKeyString) else: with file(public_key) as f: publicKeyString = f.read() with file(private_key) as f: privateKeyString = f.read() return publicKeyString, privateKeyString
def getDSAKeys(cfg): public_key = cfg.get('honeypot', 'dsa_public_key') private_key = cfg.get('honeypot', 'dsa_private_key') if not (os.path.exists(public_key) and os.path.exists(private_key)): log.msg("Generating new DSA keypair...") from Crypto.PublicKey import DSA from twisted.python import randbytes KEY_LENGTH = 1024 dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom) publicKeyString = keys.Key(dsaKey).public().toString('openssh') privateKeyString = keys.Key(dsaKey).toString('openssh') with file(public_key, 'w+b') as f: f.write(publicKeyString) with file(private_key, 'w+b') as f: f.write(privateKeyString) else: with file(public_key) as f: publicKeyString = f.read() with file(private_key) as f: privateKeyString = f.read() return publicKeyString, privateKeyString
def getDSAKeys(cfg): """ """ publicKeyFile = cfg.get("honeypot", "dsa_public_key") privateKeyFile = cfg.get("honeypot", "dsa_private_key") if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)): log.msg("Generating new DSA keypair...") from Crypto.PublicKey import DSA from twisted.python import randbytes KEY_LENGTH = 1024 dsaKey = DSA.generate(KEY_LENGTH, randbytes.secureRandom) publicKeyString = keys.Key(dsaKey).public().toString("openssh") privateKeyString = keys.Key(dsaKey).toString("openssh") with open(publicKeyFile, "w+b") as f: f.write(publicKeyString) with open(privateKeyFile, "w+b") as f: f.write(privateKeyString) else: with open(publicKeyFile, "r") as f: publicKeyString = f.read() with open(privateKeyFile, "r") as f: privateKeyString = f.read() return publicKeyString, privateKeyString
from Crypto.PublicKey import RSA from Crypto import Random import DarkCloudCryptoLib as dcCryptoLib import hashlib import sys import os from Crypto.Random import random from Crypto.PublicKey import DSA from Crypto.Hash import SHA message = "hello" key = DSA.generate(1024, lambda n: "a") h = SHA.new(message).digest() k = random.StrongRandom().randint(1,key.q-1) sig = key.sign(h, k) if key.verify(h,sig): print "OK" else: print "Incorrect signature"
_fastmath = None if _fastmath is not None: raise SystemError("Bug in DSA implementation. Please generate a " "key using a python installation that does not " "provide the Crypto.PublicKey._fastmath module.") import pickle from Crypto.PublicKey import DSA as pklib from Crypto.Util import randpool r = randpool.KeyboardRandomPool() r.randomize() pub_key_file = open(pub_key_path, 'wb') pri_key_file = open(pri_key_path, 'wb') r.add_event() key = pklib.generate(2**10, r.get_bytes) pickle.dump(key , pri_key_file, protocol=2) pickle.dump(key.publickey(), pub_key_file, protocol=2)
def generate_dsa_key(size): """ Generate a fresh, new, DSA key object where size is the size of the key object """ key = DSA.generate(size) return key
from cryptography.hazmat import backends from cryptography.hazmat.primitives.asymmetric import dsa from cryptography.hazmat.primitives.asymmetric import rsa from Crypto.PublicKey import DSA from Crypto.PublicKey import RSA # Correct dsa.generate_private_key(key_size=2048, backend=backends.default_backend()) rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backends.default_backend()) DSA.generate(bits=2048) RSA.generate(bits=2048) # Also correct: without keyword args dsa.generate_private_key(4096, backends.default_backend()) rsa.generate_private_key(3, 4096, backends.default_backend()) DSA.generate(4096) RSA.generate(4096) # Incorrect: weak key sizes dsa.generate_private_key(key_size=1024, backend=backends.default_backend()) rsa.generate_private_key(public_exponent=65537, key_size=1024, backend=backends.default_backend())
from Crypto.Random import random from Crypto.PublicKey import DSA from Crypto.Hash import SHA ################################ # LINKABLE RING SIGNATURE CODE ################################ key = DSA.generate(1024) p = key.p q = key.q g = key.g # generate private keys x1 = random.StrongRandom().randint(1,q-1) x2 = random.StrongRandom().randint(1,q-1) # get public keys y1 = pow(g,x1,p) y2 = pow(g,x2,p) tuple1 = (y1,g,p,q,x1) tuple2 = (y2,g,p,q,x2) # get the 2 DSA keys key1 = DSA.construct(tuple1) key2 = DSA.construct(tuple2) # define the hash functions def H1(message): # hash the message
def generate(cls): privkey = DSA.generate(1024) return cls((privkey.key.y, privkey.key.g, privkey.key.p, privkey.key.q, privkey.key.x), private=True)
from cryptography.hazmat.primitives.asymmetric import rsa from Crypto.PublicKey import DSA as pycrypto_dsa from Crypto.PublicKey import RSA as pycrypto_rsa from Cryptodome.PublicKey import DSA as pycryptodomex_dsa from Cryptodome.PublicKey import RSA as pycryptodomex_rsa # Correct dsa.generate_private_key(key_size=2048, backend=backends.default_backend()) ec.generate_private_key(curve=ec.SECP384R1, backend=backends.default_backend()) rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backends.default_backend()) pycrypto_dsa.generate(bits=2048) pycrypto_rsa.generate(bits=2048) pycryptodomex_dsa.generate(bits=2048) pycryptodomex_rsa.generate(bits=2048) # Also correct: without keyword args dsa.generate_private_key(4096, backends.default_backend()) ec.generate_private_key(ec.SECP256K1, backends.default_backend()) rsa.generate_private_key(3, 4096, backends.default_backend()) pycrypto_dsa.generate(4096) pycrypto_rsa.generate(4096) pycryptodomex_dsa.generate(4096)
def generateDSAkey(options): from Crypto.PublicKey import DSA print 'Generating public/private dsa key pair.' key = DSA.generate(int(options['bits']), common.entropy.get_bytes) _saveKey(key, options)
def init_key(self): self.dsa_key = DSA.generate(1024)
import pwn from Crypto.PublicKey import RSA, DSA from Crypto.Random import random, atfork from Crypto.Cipher import PKCS1_OAEP _server_pub_enc = RSA.importKey('-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGRrsdIqf8K39Ncwzsi9k2lr5G\nJ8aEFkYGrYqOQRbU5xOReMj8wWHgnSUC0fjH0gjffGiUC2HfrrNIQvXKGiSBetOu\nIWOmFiESG8IhrPyvLwX53NbMWeCihzbYGJxGyiL0bvDHxqDxzuvteSaEfNm1miPA\nQ9rs5vFnHM0R3kFjdQIDAQAB\n-----END PUBLIC KEY-----') server_pub_enc = PKCS1_OAEP.new(_server_pub_enc) dsakey = DSA.generate(512) parts = ','.join([str(p) for p in [dsakey.y, dsakey.g, dsakey.p, dsakey.q]]) parts_encrypted = [] for i in range(len(parts)/40+1): part = parts[i*40:(i+1)*40] print part part_encrypted = server_pub_enc.encrypt(part).encode('hex') parts_encrypted.append(part_encrypted) r = pwn.remote("52.6.11.111", 4321) r.send(','.join(parts_encrypted)) print r.recvuntil("communications\n") print r.recvuntil('\n') # Only winning move is to play print r.recvuntil('game?\n') print r.recvuntil('\n') r.send(str(100000000000000000000000000) + '\n') print r.recvuntil('\n') print r.recvuntil('\n')
def getSymTimings(self, testString): """ Executes the different types of symetric encryption algorithms on given string """ # RSA rp = randpool.RandomPool() t1 = time.time() rsaKey = RSA.generate(1024, rp.get_bytes) t2 = time.time() print 'RSA key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = rsaKey.encrypt(testString,"") t2 = time.time() print 'RSA encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = rsaKey.decrypt(encString) t2 = time.time() print 'RSA decryption took: %0.3fms.' % ((t2-t1)*1000.) # DSA rp = randpool.RandomPool() t1 = time.time() dsaKey = DSA.generate(1024, rp.get_bytes) t2 = time.time() print 'DSA key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = dsaKey.sign(testString,1024) t2 = time.time() print 'DSA signing took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() hash = MD5.new(testString).digest() encString = dsaKey.verify(hash,encString) t2 = time.time() print 'DSA verifying took: %0.3fms.' % ((t2-t1)*1000.) # AES t1 = time.time() aesKey = AES.new('abcdabcdabcdabcdabcdabcdabcdabcd') t2 = time.time() print 'AES key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = aesKey.encrypt(testString) t2 = time.time() print 'AES encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = aesKey.decrypt(encString) t2 = time.time() print 'AES decryption took: %0.3fms.' % ((t2-t1)*1000.) # DES t1 = time.time() desKey = DES.new('abcdabcd') t2 = time.time() print 'DES key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = desKey.encrypt(testString) t2 = time.time() print 'DES encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = desKey.decrypt(encString) t2 = time.time() print 'DES decryption took: %0.3fms.' % ((t2-t1)*1000.) # DES3 t1 = time.time() des3Key = DES3.new('abcdabcdabcdabcd') t2 = time.time() print 'DES3 key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = des3Key.encrypt(testString) t2 = time.time() print 'DES3 encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = des3Key.decrypt(encString) t2 = time.time() print 'DES3 decryption took: %0.3fms.' % ((t2-t1)*1000.) # Blowfish t1 = time.time() blowfishKey = Blowfish.new('abcdabcdabcdabcdabcdabcdabcdabcd') t2 = time.time() print 'Blowfish key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = blowfishKey.encrypt(testString) t2 = time.time() print 'Blowfish encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = blowfishKey.decrypt(encString) t2 = time.time() print 'Blowfish decryption took: %0.3fms.' % ((t2-t1)*1000.) # RC5 t1 = time.time() rc5Key = RC5.new('abcdabcdabcdabcd') t2 = time.time() print 'RC5 key generation took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = rc5Key.encrypt(testString) t2 = time.time() print 'RC5 encryption took: %0.3fms.' % ((t2-t1)*1000.) t1 = time.time() encString = rc5Key.decrypt(encString) t2 = time.time() print 'RC5 decryption took: %0.3fms.' % ((t2-t1)*1000.)
def generateDSAkey(options): from Crypto.PublicKey import DSA print 'Generating public/private dsa key pair.' key = DSA.generate(int(options['bits']), randbytes.secureRandom) _saveKey(key, options)
@arg msg ... message to sign @arg k ... override random k ''' k = k or random.StrongRandom().randint(1, privkey.q-1) # generate msg hash # sign the messages using privkey h = SHA.new(msg).digest() r,s = privkey.sign(h,k) return msg,h,(r,s),privkey.publickey() if __name__=="__main__": LOG.setLevel(logging.DEBUG) logging.debug("-- on --") LOG.debug("-- Generating private key and signing 2 messages --") # Generate new DSA pub/private key pair secret_key = DSA.generate(1024) # choose a "random" - k :) this time random is static in order to allow this attack to work k = random.StrongRandom().randint(1, secret_key.q-1) # sign two messages using the same k mA = signMessage(secret_key,"This is a signed message!",k) mB = signMessage(secret_key,"Another signed Message - I am the only one that may sign these messages :)",k) # # -- create another set of data -- secret_key2 = DSA.generate(1024) # k = random.StrongRandom().randint(1, secret_key2.q-1) m5 = signMessage(secret_key2,"xxx This is a signed message!",k) m6 = signMessage(secret_key2,"xxx Another signed Message - I am the only one that may sign these messages :)",k=0xaf) m7 = signMessage(secret_key2,"xxx Another signed xxxMessage - I am the only one that may sign these messages :)",k) m8 = signMessage(secret_key2,"xxx Another signed xxxxxxMessage - I am the only one that may sign these messages :)") print m7,m7[3].q,m7[3].g,k,m7[3].p
def create (self, size=1024): key = DSA.generate (size) self.private_key = (key.p, key.q, key.g, key.y, key.x) self.public_key = (key.p, key.q, key.g, key.y)