Esempio n. 1
0
    def test_get_rsa(self):
        """
        Testing retrieving the RSA key from the PKey instance.
        """
        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertIsInstance(rsa, RSA.RSA)
        pkey = EVP.PKey()
        pkey.assign_rsa(rsa)
        rsa2 = pkey.get_rsa()
        self.assertIsInstance(rsa2, RSA.RSA_pub)
        self.assertEqual(rsa.e, rsa2.e)
        self.assertEqual(rsa.n, rsa2.n)
        # FIXME
        # hanging call is
        #     m2.rsa_write_key(self.rsa, bio._ptr(), ciph, callback)s
        # from RSA.py/save_key_bio

        pem = rsa.as_pem(callback=self._pass_callback)
        pem2 = rsa2.as_pem()
        assert pem
        assert pem2
        self.assertNotEqual(pem, pem2)

        message = b'This is the message string'
        digest = hashlib.sha1(message).digest()
        self.assertEqual(rsa.sign(digest), rsa2.sign(digest))

        rsa3 = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertNotEqual(rsa.sign(digest), rsa3.sign(digest))
Esempio n. 2
0
    def test_get_rsa(self):
        """
        Testing retrieving the RSA key from the PKey instance.
        """
        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertIsInstance(rsa, RSA.RSA)
        pkey = EVP.PKey()
        pkey.assign_rsa(rsa)
        rsa2 = pkey.get_rsa()
        self.assertIsInstance(rsa2, RSA.RSA_pub)
        self.assertEqual(rsa.e, rsa2.e)
        self.assertEqual(rsa.n, rsa2.n)
        # FIXME
        # hanging call is
        #     m2.rsa_write_key(self.rsa, bio._ptr(), ciph, callback)s
        # from RSA.py/save_key_bio

        pem = rsa.as_pem(callback=self._pass_callback)
        pem2 = rsa2.as_pem()
        assert pem
        assert pem2
        self.assertNotEqual(pem, pem2)

        message = b'This is the message string'
        digest = hashlib.sha1(message).digest()
        self.assertEqual(rsa.sign(digest), rsa2.sign(digest))

        rsa3 = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertNotEqual(rsa.sign(digest), rsa3.sign(digest))
Esempio n. 3
0
    def _create_new_rsa_key_pairs(self):
        """ Creates a new rsa key-pair. """

        def _blank_callback(self):
            "Replace the default dashes as output upon key generation"
            return
        algorithm = 'rsa'
        for mode, key_pair in Cryptor._VALID_MODES.get(algorithm).iteritems():
            # Random seed
            Rand.rand_seed(os.urandom(Cryptor.RSA_KEY_LENGTH))
            # Generate key pair
            key = RSA.gen_key(Cryptor.RSA_KEY_LENGTH, 65537, _blank_callback)
            # create and save the public key to file
            filename = key_pair.get('public', None)
            if key.save_pub_key(''.join(filename)) > 0:
                print '(*) Created new {0} {1} {2}'.format(algorithm, mode, filename)
            else:
                print '( ) Failed to create new {0} {1} {2}'.format(algorithm, mode, filename)
            # create and save the private key to file
            filename = key_pair.get('private', None)
            # key.save_key('user-private-local.pem'), e.g if suffix=''
            if filename:
                if key.save_key(''.join(filename), None) > 0:
                    print '(*) Created new {0} {1} key {2}'.format(algorithm, mode, filename)
                else:
                    print '( ) Failed to create new {0} {1} key {2}'.format(algorithm, mode, filename)
Esempio n. 4
0
  def _LoadOurCertificate(self):
    """Loads an RSA key from the certificate.

    If no certificate is found, or it is invalid, we make a new random RSA key,
    and store it as our certificate.

    Returns:
      An RSA key - either from the certificate or a new random key.
    """
    try:
      # This is our private key - make sure it has no password set.
      rsa = RSA.load_key_string(str(self.private_key), callback=lambda x: "")
      self._ParseRSAKey(rsa)

      logging.info("Starting client %s", self.common_name)
    except (X509.X509Error, RSA.RSAError):
      # 65537 is the standard value for e
      rsa = RSA.gen_key(self.BITS, 65537, lambda: None)

      self._ParseRSAKey(rsa)
      logging.info("Client pending enrolment %s", self.common_name)

      # Make new keys
      pk = EVP.PKey()
      pk.assign_rsa(rsa)

      # Save the keys
      self.SavePrivateKey(pk)

    return rsa
Esempio n. 5
0
def generate_keypair():
    pk = RSA.gen_key(2048, m2.RSA_F4, lambda x: None)
    private = pk.as_pem(None)
    pu = BIO.MemoryBuffer()
    pk.save_pub_key_bio(pu)
    public = pu.read()
    return private, public
Esempio n. 6
0
    def add(self, keypair):
        """
        Add a keypair
        """
        LOG.info('add(keypair=%s)', keypair)

        # Generate a new keypair if the request doesn't contain a public key
        if 'public_key' in keypair:
            public_key = keypair['public_key']
            private_key = None
        else:
            key = RSA.gen_key(1024, 65537, callback=lambda: None)
            public_key = 'ssh-rsa %s' % b64encode(key.pub()[1])
            private_key = key.as_pem(cipher=None)

        # Calculate the key fingerprint
        fp_plain = md5(b64decode(public_key.split()[1])).hexdigest()
        fp = ':'.join(a + b for (a, b) in zip(fp_plain[::2], fp_plain[1::2]))

        # Create the new keypair in the database
        new_keypair = DB.keypairs.create(name=keypair['name'], fingerprint=fp,
                                         public_key=public_key)

        if private_key is None:
            return utils.sanitize(new_keypair, KEYPAIRS_INFO)

        new_keypair['private_key'] = private_key
        return utils.sanitize(new_keypair, KEYPAIRS_INFO + ('private_key', ))
Esempio n. 7
0
    def generate_cert_key_pair(self):
        private_key = EVP.PKey()
        rsa = M2RSA.gen_key(2048, 65537, lambda: None)
        private_key.assign_rsa(rsa)

        req = X509.Request()
        req.set_pubkey(private_key)
        name = req.get_subject()
        name.CN = 'NVIDIA GameStream Client'
        req.sign(private_key, 'sha1')

        public_key = req.get_pubkey()
        cert = X509.X509()
        cert.set_serial_number(1)
        cert.set_version(2)
        self.validate_cert(cert)
        cert.set_issuer(name)
        cert.set_subject(cert.get_issuer())
        cert.set_pubkey(public_key)
        cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE', 1))
        cert.add_ext(X509.new_extension('keyUsage', 'keyCertSign, cRLSign', 1))
        cert.add_ext(
            X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint()))
        cert.sign(private_key, 'sha1')

        cert.save(self.cert_file, 1)

        with open(self.key_file, 'wb') as key_file:
            key_file.write(private_key.as_pem(None))
            key_file.close()

        self.load_cert_key_pair()
Esempio n. 8
0
def m2c_key(arg1, arg2):
    try:
        rsa = RSA.gen_key(1024, 3, lambda *agr:None)
        pub_bio = BIO.MemoryBuffer()
        priv_bio = BIO.MemoryBuffer()

        rsa.save_pub_key_bio(pub_bio)
        rsa.save_key_bio(priv_bio, None)
        
        pub_file = arg1 
       # pub_file = arg1 + 'pub.pem'
        private_file = arg2 
       # private_file = arg2 + 'private.pem'
        open(pub_file,'w').write(pub_bio.read_all())
        open(private_file,'w').write(priv_bio.read_all())

        pub_key = RSA.load_pub_key(pub_file)
        priv_key = RSA.load_key(private_file)

        message = 'opzoon'
  
        encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
        decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)

        if decrypted==message:
            #os.popen("rm -rf m2crypto_gen_key.py")
            pass
        else:
            os.popen("rm -rf *.pem")
            print "Key generation failed,please try again!"
            raise Exception("Key generation failed,please try again!")
    except Exception,e:
        os.popen("rm -rf *.pem")
        raise Exception("Key generation failed,please try again!")
Esempio n. 9
0
    def do_GET(self):
        print 'Generating RSA Key'
        key = RSA.gen_key(1024, 65337)
        raw_key = key.pub()[1]
        self.b64key = b64encode(raw_key)
        print self.b64key
        try:
            if self.path.endswith(".html"):
                f = open(curdir + sep + self.path) #self.path has /test.html
#note that this potentially makes every file on your computer readable by the internet

                self.send_response(200)
                self.send_header('Content-type',	'text/html')
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
                return
            if self.path.endswith("getpub.esp"):   #our dynamic content
                self.send_response(200)
                self.send_header('Content-type',	'text/html')
                self.end_headers()
                self.wfile.write(self.b64key)
                return
                
            return
                
        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)
Esempio n. 10
0
 def _gen_key(self, do_assign):
     pk = EVP.PKey()
     k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
     if do_assign:
         # apparently, this operation breaks save_key later ok
         pk.assign_rsa(k, capture=False)
     return k
Esempio n. 11
0
    def mkreq(self, bits, ca=0):
        pk = EVP.PKey()
        x = X509.Request()
        rsa = RSA.gen_key(bits, 65537, self.callback)
        pk.assign_rsa(rsa)
        rsa = None  # should not be freed here
        x.set_pubkey(pk)
        name = x.get_subject()
        name.C = "UK"
        name.CN = "OpenSSL Group"
        if not ca:
            ext1 = X509.new_extension('subjectAltName',
                                      'DNS:foobar.example.com')
            ext2 = X509.new_extension('nsComment', 'Hello there')
            extstack = X509.X509_Extension_Stack()
            extstack.push(ext1)
            extstack.push(ext2)
            x.add_extensions(extstack)

        with self.assertRaises(ValueError):
            x.sign(pk, 'sha513')

        x.sign(pk, 'sha1')
        self.assertTrue(x.verify(pk))
        pk2 = x.get_pubkey()
        self.assertTrue(x.verify(pk2))
        return x, pk
def write_new_certificate(
        public_key_path, cert_path, subject, expiry_days=3560):
    """Create X509 certificate and private key

    http://www.openssl.org/docs/apps/req.html
    http://www.madboa.com/geek/openssl/
    https://pyopenssl.readthedocs.io/en/stable/api/crypto.html#certificates

    """

    rsa = RSA.gen_key(2048, 65537, lambda: None)

    public_key = EVP.PKey()
    public_key.assign_rsa(rsa)
    public_key.save_key(public_key_path, cipher=None)

    cert = X509.X509()

    cert.set_serial_number(1)
    cert.set_version(2)

    cert.set_not_before(asn_expiry(0))
    cert.set_not_after(asn_expiry(expiry_days))

    cert.set_pubkey(public_key)

    name = dict_to_x509_name(subject)
    cert.set_issuer(name)
    cert.set_subject(name)

    cert.sign(public_key, 'sha1')

    cert.save(cert_path)
Esempio n. 13
0
def genPrivKey():
    """ 生成私钥
    """
    bio=BIO.MemoryBuffer()
    rsa=RSA.gen_key(2048, 65537, lambda *arg:None)
    rsa.save_key_bio(bio, None)
    return bio.read_all()
Esempio n. 14
0
 def _create(self, hostname='localhost'):
     # Make the RSA key
     self.rsakey = RSA.gen_key(2048, m2.RSA_F4)
     if self.secure:
         # Save the key, AES256-CBC encrypted
         self.rsakey.save_key(self.keyfile, 'aes_256_cbc')
     else:
         # Save the key unencrypted.
         self.rsakey.save_key(self.keyfile,
                              None,
                              callback=m2util.no_passphrase_callback)
     # Make the public key
     pkey = EVP.PKey()
     pkey.assign_rsa(self.rsakey, 0)
     # Generate the certificate
     self.cert = X509.X509()
     self.cert.set_serial_number(long(bttime()))
     self.cert.set_version(0x2)
     self.cert.set_pubkey(pkey)
     # Set the name on the certificate
     name = X509.X509_Name()
     name.CN = hostname
     self.cert.set_subject(name)
     self.cert.set_issuer(name)
     # Set the period of time the cert is valid for (5 years from issue)
     notBefore = m2.x509_get_not_before(self.cert.x509)
     notAfter = m2.x509_get_not_after(self.cert.x509)
     m2.x509_gmtime_adj(notBefore, 0)
     m2.x509_gmtime_adj(notAfter, 60 * 60 * 24 * 365 * 5)
     # Sign the certificate
     self.cert.sign(pkey, 'sha1')
     # Save it
     self.cert.save_pem(self.certfile)
Esempio n. 15
0
 def _create(self, hostname='localhost'):
     # Make the RSA key
     self.rsakey = RSA.gen_key(2048, m2.RSA_F4)
     if self.secure:
         # Save the key, AES256-CBC encrypted
         self.rsakey.save_key(self.keyfile, 'aes_256_cbc')
     else:
         # Save the key unencrypted.
         self.rsakey.save_key(self.keyfile, None, callback=m2util.no_passphrase_callback)
     # Make the public key
     pkey = EVP.PKey()
     pkey.assign_rsa(self.rsakey, 0)
     # Generate the certificate
     self.cert = X509.X509()
     self.cert.set_serial_number(long(bttime()))
     self.cert.set_version(0x2)
     self.cert.set_pubkey(pkey)
     # Set the name on the certificate
     name = X509.X509_Name()
     name.CN = hostname
     self.cert.set_subject(name)
     self.cert.set_issuer(name)
     # Set the period of time the cert is valid for (5 years from issue)
     notBefore = m2.x509_get_not_before(self.cert.x509)
     notAfter = m2.x509_get_not_after(self.cert.x509)
     m2.x509_gmtime_adj(notBefore, 0)
     m2.x509_gmtime_adj(notAfter, 60*60*24*365*5)
     # Sign the certificate
     self.cert.sign(pkey, 'sha1')
     # Save it
     self.cert.save_pem(self.certfile)
    def mkreq(self, bits, ca=0):
        pk = EVP.PKey()
        x = X509.Request()
        rsa = RSA.gen_key(bits, 65537, self.callback)
        pk.assign_rsa(rsa)
        rsa = None  # should not be freed here
        x.set_pubkey(pk)
        name = x.get_subject()
        name.C = "UK"
        name.CN = "OpenSSL Group"
        if not ca:
            ext1 = X509.new_extension('subjectAltName',
                                      'DNS:foobar.example.com')
            ext2 = X509.new_extension('nsComment', 'Hello there')
            extstack = X509.X509_Extension_Stack()
            extstack.push(ext1)
            extstack.push(ext2)
            x.add_extensions(extstack)

        with self.assertRaises(ValueError):
            x.sign(pk, 'sha513')

        x.sign(pk, 'sha1')
        self.assertTrue(x.verify(pk))
        pk2 = x.get_pubkey()
        self.assertTrue(x.verify(pk2))
        return x, pk
Esempio n. 17
0
    def generate_keys(self,
                      cr,
                      uid,
                      ids,
                      key_length=1024,
                      key_gen_number=0x10001,
                      context=None):
        """
        Generate key pairs: private and public.
        """
        if context is None:
            context = {}
        for signer in self.browse(cr, uid, ids):
            # Random seed
            Rand.rand_seed(os.urandom(key_length))
            # Generate key pair
            key = RSA.gen_key(key_length, key_gen_number, lambda *x: None)
            # Create memory buffers
            pri_mem = BIO.MemoryBuffer()
            pub_mem = BIO.MemoryBuffer()
            # Save keys to buffers
            key.save_key_bio(pri_mem, None)
            key.save_pub_key_bio(pub_mem)

            w = {
                'key': pri_mem.getvalue(),
                'pub': pub_mem.getvalue(),
            }
            self.write(cr, uid, signer.id, w)
        return True
Esempio n. 18
0
    def make_proxycert(self, eecert):
        proxycert = X509.X509()
        pk2 = EVP.PKey()
        proxykey = RSA.gen_key(1024, 65537, self.callback)
        pk2.assign_rsa(proxykey)
        proxycert.set_pubkey(pk2)
        proxycert.set_version(2)
        not_before = ASN1.ASN1_UTCTIME()
        not_after = ASN1.ASN1_UTCTIME()
        not_before.set_time(int(time.time()))
        offset = 12 * 3600
        not_after.set_time(int(time.time()) + offset)
        proxycert.set_not_before(not_before)
        proxycert.set_not_after(not_after)
        proxycert.set_issuer_name(eecert.get_subject())
        proxycert.set_serial_number(12345678)
        issuer_name_string = eecert.get_subject().as_text()
        seq = issuer_name_string.split(",")

        subject_name = X509.X509_Name()
        for entry in seq:
            l = entry.split("=")
            subject_name.add_entry_by_txt(field=l[0].strip(),
                                          type=ASN1.MBSTRING_ASC,
                                          entry=l[1], len=-1, loc=-1, set=0)

        subject_name.add_entry_by_txt(field="CN", type=ASN1.MBSTRING_ASC,
                                      entry="Proxy", len=-1, loc=-1, set=0)

        proxycert.set_subject_name(subject_name)
        # XXX leaks 8 bytes
        pci_ext = X509.new_extension("proxyCertInfo",
                                     "critical,language:Inherit all", 1)
        proxycert.add_ext(pci_ext)
        return proxycert
Esempio n. 19
0
 def generate_minion_keys(self):
     # XXX TODO: Replace M2Crypto with PyCrypto
     # see: https://github.com/saltstack/salt/pull/1112/files
     # generate keys
     keyname = self.get_keyname()
     if not keyname:
         LOG.error("Must specify salt_id or hostname")
         return False
     gen = RSA.gen_key(2048, 1, callback=lambda x, y, z: None)
     pubpath = os.path.join(self.pki_dir, "{0}.pub".format(keyname))
     gen.save_pub_key(pubpath)
     LOG.info("public key {0}".format(pubpath))
     if self.config.get("save_keys"):
         cumask = os.umask(191)
         gen.save_key(os.path.join(self.pki_dir, "{0}.pem".format(keyname)), None)
         os.umask(cumask)
     # public key
     _pub = TemporaryFile()
     bio_pub = BIO.File(_pub)
     m2.rsa_write_pub_key(gen.rsa, bio_pub._ptr())
     _pub.seek(0)
     self.config["public_key"] = self.public_key = _pub.read()
     self.config["formatted_public_key"] = "\n".join("    {0}".format(k) for k in self.public_key.split("\n"))
     # private key
     _pem = TemporaryFile()
     bio_pem = BIO.File(_pem)
     gen.save_key_bio(bio_pem, None)
     _pem.seek(0)
     self.config["private_key"] = self.private_key = _pem.read()
     self.config["formatted_private_key"] = "\n".join("    {0}".format(k) for k in self.private_key.split("\n"))
     return True
Esempio n. 20
0
def gen_keys(keydir, keyname, keysize, user=None):
    '''
    Generate a RSA public keypair for use with salt

    :param str keydir: The directory to write the keypair to
    :param str keyname: The type of salt server for whom this key should be written. (i.e. 'master' or 'minion')
    :param int keysize: The number of bits in the key
    :param str user: The user on the system who should own this keypair

    :rtype: str
    :return: Path on the filesystem to the RSA private key
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)

    gen = RSA.gen_key(keysize, 65537, callback=lambda x, y, z: None)
    cumask = os.umask(191)
    gen.save_key(priv, None)
    os.umask(cumask)
    gen.save_pub_key(pub)
    os.chmod(priv, 256)
    if user:
        try:
            import pwd
            uid = pwd.getpwnam(user).pw_uid
            os.chown(priv, uid, -1)
            os.chown(pub, uid, -1)
        except (KeyError, ImportError, OSError):
            # The specified user was not found, allow the backup systems to
            # report the error
            pass
    return priv
Esempio n. 21
0
def create_rsa_keyring(passphrase_callback, key_size=2048, exponent=65537):
    """ Return a new RSA keyring as tuple (<public key>, <private key>)
    @param passphrase_callback: A Python callable object that is invoked
    during key generation; its usual purpose is to provide visual
    feedback.
    You must load a randpool file before calling this method with
    Rand.load_file('randpool', -1).
    After calling the method, you must save the randpool file with
    Rand.save_file('randpool')
    @type passphrase_callback: Callback

    @param key_size: Key length, in bits
    @type key_size: Integer

    @param exponent: The RSA public exponent
    @type exponent: Integer
    """
    keyring = RSA.gen_key(key_size, exponent)

    privkey_filename = get_secure_filename()
    pubkey_filename = get_secure_filename()

    keyring.save_key(privkey_filename, callback=passphrase_callback)
    keyring.save_pub_key(pubkey_filename)

    privkey = RSA.load_key(privkey_filename, callback=passphrase_callback)
    pubkey = RSA.load_pub_key(pubkey_filename)

    os.unlink(privkey_filename)
    os.unlink(pubkey_filename)

    return (pubkey, privkey)
Esempio n. 22
0
File: key.py Progetto: grith/gsindl
def generate_key(key=None, keySize=2048, callback=no_passphrase_callback):
    """This is a wrapper class for handling key pair generation.

    :param key: the :class:`str` or file path to the key
    :param keySize: The size of the key to be generated (default 2048)
    :param callback: a function that is called when outputting the key,
       it's used to encrypt the key before writing it.

    """
    if isinstance(key, str):
        key = key.strip()
        if key.startswith("-----BEGIN RSA PRIVATE KEY-----"):
            bio = BIO.MemoryBuffer(key)
            _key = RSA.load_key_bio(bio, callback)
        elif path.exists(key):
            keyfile = open(key)

            bio = BIO.File(keyfile)
            key = RSA.load_key_bio(bio, callback)

            _pubkey = EVP.PKey()
            _key = key
            _pubkey.assign_rsa(_key)
        else:
            raise ValueError("WTF")
    else:
        _pubkey = EVP.PKey()
        _key = RSA.gen_key(keySize, m2.RSA_F4, callback=quiet_keygen_callback)
        _pubkey.assign_rsa(_key)
    return _pubkey
Esempio n. 23
0
File: cs.py Progetto: sr-gi/paysense
    def generate_certificate(
        self,
        aca_cert,
        btc_address=None,
        pkey=None,
    ):

        if pkey is None and btc_address is None:
            pkey, btc_address = self.generate_keys()
            self.btc_address = btc_address

        issuer = aca_cert.get_issuer()

        # Creating a certificate
        cert = X509.X509()

        # Set issuer
        cert.set_issuer(issuer)

        # Generate CS information
        cert_name = X509.X509_Name()
        cert_name.C = 'CT'
        cert_name.ST = 'Barcelona'
        cert_name.L = 'Bellaterra'
        cert_name.O = 'UAB'
        cert_name.OU = 'DEIC'
        cert_name.CN = btc_address
        cert.set_subject_name(cert_name)

        # Set public_key
        cert.set_pubkey(pkey)

        # Time for certificate to stay valid
        cur_time = ASN1.ASN1_UTCTIME()
        cur_time.set_time(int(time()))
        # Expire certs in 1 year.
        expire_time = ASN1.ASN1_UTCTIME()
        expire_time.set_time(int(time()) + 60 * 60 * 24 * 365)
        # Set the validity
        cert.set_not_before(cur_time)
        cert.set_not_after(expire_time)

        # Sign the certificate using the same key type the CA is going to use later
        # The resulting signature will not be used, it is only for setting the corresponding field into the certificate
        rsa_keys = RSA.gen_key(2046, 65537, callback=lambda x, y, z: None)
        rsa_pkey = EVP.PKey()
        rsa_pkey.assign_rsa(rsa_keys)
        cert.sign(rsa_pkey, md='sha256')

        # Load the Certificate as a ASN.1 object and extract the TBS Certificate (special thanks to Alex <*****@*****.**>)
        asn1_cert = decoder.decode(cert.as_der(), asn1Spec=Certificate())[0]
        tbs = asn1_cert.getComponentByName("tbsCertificate")

        # Compute the sha256 of the TBS Certificate
        tbs_der = encoder.encode(tbs)
        digest = sha256()
        digest.update(tbs_der)
        cert_hash = digest.digest()

        return asn1_cert, cert_hash
Esempio n. 24
0
def gen_keys(keydir, keyname, keysize, user=None):
    '''
    Generate a keypair for use with salt
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)

    gen = RSA.gen_key(keysize, 65537, callback=lambda x, y, z: None)
    cumask = os.umask(191)
    gen.save_key(priv, None)
    os.umask(cumask)
    gen.save_pub_key(pub)
    os.chmod(priv, 256)
    if user:
        try:
            import pwd
            uid = pwd.getpwnam(user).pw_uid
            os.chown(priv, uid, -1)
            os.chown(pub, uid, -1)
        except (KeyError, ImportError, OSError):
            # The specified user was not found, allow the backup systems to
            # report the error
            pass
    return priv
Esempio n. 25
0
    def generate_cert_key_pair(self):
        private_key = EVP.PKey()
        rsa = M2RSA.gen_key(2048, 65537, lambda: None)
        private_key.assign_rsa(rsa)

        req = X509.Request()
        req.set_pubkey(private_key)
        name = req.get_subject()
        name.CN = "NVIDIA GameStream Client"
        req.sign(private_key, "sha1")

        public_key = req.get_pubkey()
        cert = X509.X509()
        cert.set_serial_number(1)
        cert.set_version(2)
        self.validate_cert(cert)
        cert.set_issuer(name)
        cert.set_subject(cert.get_issuer())
        cert.set_pubkey(public_key)
        cert.add_ext(X509.new_extension("basicConstraints", "CA:TRUE", 1))
        cert.add_ext(X509.new_extension("keyUsage", "keyCertSign, cRLSign", 1))
        cert.add_ext(X509.new_extension("subjectKeyIdentifier", cert.get_fingerprint()))
        cert.sign(private_key, "sha1")

        cert.save(self.cert_file, 1)

        with open(self.key_file, "wb") as key_file:
            key_file.write(private_key.as_pem(None))
            key_file.close()

        self.load_cert_key_pair()
Esempio n. 26
0
def gen_keys(keydir, keyname, keysize, user=None):
    '''
    Generate a keypair for use with salt
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)

    gen = RSA.gen_key(keysize, 65537, callback=lambda x, y, z: None)
    cumask = os.umask(191)
    gen.save_key(priv, None)
    os.umask(cumask)
    gen.save_pub_key(pub)
    os.chmod(priv, 256)
    if user:
        try:
            import pwd
            uid = pwd.getpwnam(user).pw_uid
            os.chown(priv, uid, -1)
            os.chown(pub, uid, -1)
        except (KeyError, ImportError, OSError):
            # The specified user was not found, allow the backup systems to
            # report the error
            pass
    return priv
Esempio n. 27
0
	def _makekey(self, name, password='', keylen=1024, cipher=DEFAULT_CIPHER):
		"""Create a RSA key.

					*private function*

					args:
						. name     : key name (filename will be 'name.key')
			. password : key password (if empty, key will be passwordless)
						. keylen   : private key size, in bits
						. cipher   : cipher used to encrypt key

					returns:
					  . the key
		"""				
		# Create private key
		rsa = RSA.gen_key(keylen, m2.RSA_F4)

		def _getpwd(*_args):
			return password
		#NOTE: when empty password, need not to use a cipher, or generated key file is empty
		rsa.save_key(self._keyfile(name),
			cipher=cipher if len(password) > 0 else None,
						callback=_getpwd)

		rsa.save_pub_key(self._pubfile(name))

		# create symlinks in /var/lib/asterisk/keys
		# (required for IAX trunks)
		os.symlink(self._keyfile(name),	os.path.join('/var/lib/asterisk/keys',name+'.key'))
		os.symlink(self._pubfile(name),	os.path.join('/var/lib/asterisk/keys',name+'.pub'))

		return rsa
Esempio n. 28
0
def main(keylen, hashalg):
    global rsa, dgst     # this exists ONLY for speed testing
    
    Rand.load_file('randpool.dat', -1) 
        
    pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen)
    pubkeyfilename = 'rsa%dpubkey.pem' % (keylen)  
    
    if makenewkey:
        print '  making and saving a new key'
        rsa = RSA.gen_key(keylen, exponent)
        rsa.save_key(pvtkeyfilename, None )  # no pswd callback
        rsa.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        rsa = RSA.load_key(pvtkeyfilename)
    print '  rsa key length:', len(rsa)
    
    if not rsa.check_key():
        raise 'key is not initialised'

    # since we are testing signing and verification, let's not 
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (hashalg, base64.encodestring(dgst))
    
    test(rsa, dgst)
#    test_asn1(rsa, dgst)
    test_speed(rsa, dgst)
    Rand.save_file('randpool.dat')
Esempio n. 29
0
File: ussl.py Progetto: darcyg/upnpy
    def _gen_certificate(type):

        from M2Crypto import EVP, RSA, X509, ASN1
        import time

        # create a key pair
        k = EVP.PKey()
        k.assign_rsa(RSA.gen_key(2048, m2.RSA_F4, lambda:None))

        # create a self-signed cert
        cert = X509.X509()
        cert.get_subject().C = "FR"
        cert.get_subject().O = "SFR"
        cert.get_subject().CN = _get_cn(type)
        cert.set_serial_number(1000)

        now = ASN1.ASN1_UTCTIME()
        now.set_time(long(time.time()))
        cert.set_not_before(now)
        
        expire = ASN1.ASN1_UTCTIME()
        expire.set_time(long(time.time())+10*365*24*60*60)
        cert.set_not_after(expire)

        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(k)
        cert.sign(k, 'sha256')

        return cert, k
Esempio n. 30
0
    def make_proxycert(self, eecert):
        proxycert = X509.X509()
        pk2 = EVP.PKey()
        proxykey = RSA.gen_key(1024, 65537, self.callback)
        pk2.assign_rsa(proxykey)
        proxycert.set_pubkey(pk2)
        proxycert.set_version(2)
        not_before = ASN1.ASN1_UTCTIME()
        not_after = ASN1.ASN1_UTCTIME()
        not_before.set_time(int(time.time()))
        offset = 12 * 3600
        not_after.set_time(int(time.time()) + offset)
        proxycert.set_not_before(not_before)
        proxycert.set_not_after(not_after)
        proxycert.set_issuer_name(eecert.get_subject())
        proxycert.set_serial_number(12345678)
        issuer_name_string = eecert.get_subject().as_text()
        seq = issuer_name_string.split(",")

        subject_name = X509.X509_Name()
        for entry in seq:
            l = entry.split("=")
            subject_name.add_entry_by_txt(field=l[0].strip(),
                                          type=ASN1.MBSTRING_ASC,
                                          entry=l[1], len=-1, loc=-1, set=0)

        subject_name.add_entry_by_txt(field="CN", type=ASN1.MBSTRING_ASC,
                                      entry="Proxy", len=-1, loc=-1, set=0)

        proxycert.set_subject_name(subject_name)
        # XXX leaks 8 bytes
        pci_ext = X509.new_extension("proxyCertInfo",
                                     "critical,language:Inherit all", 1)
        proxycert.add_ext(pci_ext)
        return proxycert
Esempio n. 31
0
    def _gen_certificate(type):

        from M2Crypto import EVP, RSA, X509, ASN1
        import time

        # create a key pair
        k = EVP.PKey()
        k.assign_rsa(RSA.gen_key(2048, m2.RSA_F4, lambda: None))

        # create a self-signed cert
        cert = X509.X509()
        cert.get_subject().C = "FR"
        cert.get_subject().O = "SFR"
        cert.get_subject().CN = _get_cn(type)
        cert.set_serial_number(1000)

        now = ASN1.ASN1_UTCTIME()
        now.set_time(long(time.time()))
        cert.set_not_before(now)

        expire = ASN1.ASN1_UTCTIME()
        expire.set_time(long(time.time()) + 10 * 365 * 24 * 60 * 60)
        cert.set_not_after(expire)

        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(k)
        cert.sign(k, 'sha256')

        return cert, k
Esempio n. 32
0
 def generate_minion_keys(self):
     #XXX TODO: Replace M2Crypto with PyCrypto
     # see: https://github.com/saltstack/salt/pull/1112/files
     # generate keys
     keyname = self.get_keyname()
     if not keyname:
         LOG.error("Must specify salt_id or hostname")
         return False
     gen = RSA.gen_key(2048, 1, callback=lambda x, y, z: None)
     pubpath = os.path.join(self.pki_dir, '{0}.pub'.format(keyname))
     gen.save_pub_key(pubpath)
     LOG.info("public key {0}".format(pubpath))
     if self.config.get('save_keys'):
         cumask = os.umask(191)
         gen.save_key(os.path.join(self.pki_dir, '{0}.pem'.format(keyname)),
                      None)
         os.umask(cumask)
     # public key
     _pub = TemporaryFile()
     bio_pub = BIO.File(_pub)
     m2.rsa_write_pub_key(gen.rsa, bio_pub._ptr())
     _pub.seek(0)
     self.config['public_key'] = self.public_key = _pub.read()
     self.config['formatted_public_key'] = '\n'.join(
         "    {0}".format(k) for k in self.public_key.split('\n'))
     # private key
     _pem = TemporaryFile()
     bio_pem = BIO.File(_pem)
     gen.save_key_bio(bio_pem, None)
     _pem.seek(0)
     self.config['private_key'] = self.private_key = _pem.read()
     self.config['formatted_private_key'] = '\n'.join(
         "    {0}".format(k) for k in self.private_key.split('\n'))
     return True
Esempio n. 33
0
 def _gen_key(self, do_assign):
     pk = EVP.PKey()
     k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
     if do_assign:
         # apparently, this operation breaks save_key later ok
         pk.assign_rsa(k, capture=False)
     return k
Esempio n. 34
0
def cliGen():
    exp = 65537
    ##key = RSA.gen_key(2048, exp, CreateCallbackCLI().genparam_callback)
    key = RSA.gen_key(2048, exp, CreateCallbackCLI())
    print key
    key.save_key('/tmp/key.pem','aes_128_cbc', SaveCallbackCLI())
    print "ok"
Esempio n. 35
0
def main(keylen, hashalg):
    global rsa, dgst  # this exists ONLY for speed testing

    Rand.load_file('randpool.dat', -1)

    pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen)
    pubkeyfilename = 'rsa%dpubkey.pem' % (keylen)

    if makenewkey:
        print '  making and saving a new key'
        rsa = RSA.gen_key(keylen, exponent)
        rsa.save_key(pvtkeyfilename, None)  # no pswd callback
        rsa.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        rsa = RSA.load_key(pvtkeyfilename)
    print '  rsa key length:', len(rsa)

    if not rsa.check_key():
        raise 'key is not initialised'

    # since we are testing signing and verification, let's not
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (hashalg, base64.encodestring(dgst))

    test(rsa, dgst)
    #    test_asn1(rsa, dgst)
    test_speed(rsa, dgst)
    Rand.save_file('randpool.dat')
Esempio n. 36
0
def gen_key(minion_id, dns_name=None, password=None, key_len=2048):
    """
    Generate and return a private_key. If a ``dns_name`` is passed in, the
    private_key will be cached under that name.

    CLI Example:

    .. code-block:: bash

        salt-run digicert.gen_key <minion_id> [dns_name] [password]
    """
    keygen_type = "RSA"

    if keygen_type == "RSA":
        if HAS_M2:
            gen = RSA.gen_key(key_len, 65537)
            private_key = gen.as_pem(cipher="des_ede3_cbc",
                                     callback=lambda x: six.b(password))
        else:
            gen = RSA.generate(bits=key_len)
            private_key = gen.exportKey("PEM", password)
        if dns_name is not None:
            bank = "digicert/domains"
            cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
            try:
                data = cache.fetch(bank, dns_name)
                data["private_key"] = private_key
                data["minion_id"] = minion_id
            except TypeError:
                data = {"private_key": private_key, "minion_id": minion_id}
            cache.store(bank, dns_name, data)
    return private_key
Esempio n. 37
0
 def test_pem(self):
     rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
     pkey = EVP.PKey()
     pkey.assign_rsa(rsa)
     assert pkey.as_pem(callback=self._pass_callback) != pkey.as_pem(cipher=None)
     self.assertRaises(ValueError, pkey.as_pem, cipher='noXX$$%%suchcipher',
                       callback=self._pass_callback)
Esempio n. 38
0
def mk_request(bits, CN, C, ST, L, O, OU):
    """Create a X509 request with the given number of bits in they key.

    :param bits: number of RSA key bits
    :param CN: Common Name field
    :param C: Country Name
    :param ST: State or province name
    :param L: Locality
    :param O: Organization
    :param OU: Organization Unit
    :returns: a X509 request and the private key (EVP)
    """
    pk = EVP.PKey()
    x = X509.Request()
    rsa = RSA.gen_key(bits, 65537, lambda: None)
    pk.assign_rsa(rsa)
    x.set_pubkey(pk)

    subject_name = X509.X509_Name()
    subject_name.add_entry_by_txt(field="CN",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=CN or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    subject_name.add_entry_by_txt(field="C",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=C or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    subject_name.add_entry_by_txt(field="ST",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=ST or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    subject_name.add_entry_by_txt(field="L",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=L or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    subject_name.add_entry_by_txt(field="O",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=O or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    subject_name.add_entry_by_txt(field="OU",
                                  type=ASN1.MBSTRING_ASC,
                                  entry=OU or "",
                                  len=-1,
                                  loc=-1,
                                  set=0)
    x.set_subject_name(subject_name)

    x.sign(pk, 'sha256')
    return x, pk
Esempio n. 39
0
def gen_rsa_key():
    conf = dummy_conf()
    if not os.path.isfile(conf.app['priv_key_path']):
        key = RSA.gen_key(2048, 65537, callback=lambda x, y, z: None)
        memory = BIO.MemoryBuffer()
        key.save_key_bio(memory, cipher=None)
        p_key = memory.getvalue()
        file(conf.app['priv_key_path'], 'w').write(p_key)
Esempio n. 40
0
def _generate_rsa_keypair(bits=2048):
    key = RSA.gen_key(bits, 65537)
    private_key = key.as_pem(cipher=None)
    rsa_privkey = rsa.key.PrivateKey.load_pkcs1(private_key, 'PEM')
    rsa_pubkey = rsa.key.PublicKey(rsa_privkey.n, rsa_privkey.e)
    public_key = rsa_pubkey.save_pkcs1('PEM')

    return private_key, public_key, key
Esempio n. 41
0
 def test_plain(self):
     '''
     generate keypair and save it
     '''
     pk = EVP.PKey()
     k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
     pk.assign_rsa(k, capture=False)
     self._save(k)
Esempio n. 42
0
 def test_plain(self):
     '''
     generate keypair and save it
     '''
     pk = EVP.PKey()
     k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
     pk.assign_rsa(k, capture=False)
     self._save(k)
Esempio n. 43
0
File: ssl.py Progetto: aureg/baruwa2
def make_key_pair(key_length=1024):
    "Make public/private keys"
    Rand.rand_seed (os.urandom (key_length))
    key = RSA.gen_key (key_length, 65537, blank_callback)
    pri_mem = BIO.MemoryBuffer()
    pub_mem = BIO.MemoryBuffer()
    key.save_key_bio(pri_mem, None)
    key.save_pub_key_bio(pub_mem)
    return pub_mem.getvalue(), pri_mem.getvalue()
Esempio n. 44
0
 def test_pem(self):
     rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
     pkey = EVP.PKey()
     pkey.assign_rsa(rsa)
     self.assertNotEqual(pkey.as_pem(callback=self._pass_callback),
                         pkey.as_pem(cipher=None))
     with self.assertRaises(ValueError):
         pkey.as_pem(cipher='noXX$$%%suchcipher',
                     callback=self._pass_callback)
Esempio n. 45
0
def make_proxy_request(bits, subject):
    pk = EVP.PKey()
    x = X509.Request()
    rsa = RSA.gen_key(bits, 65537, lambda: None)
    pk.assign_rsa(rsa)
    x.set_pubkey(pk)
    x.set_subject(subject)
    x.sign(pk, 'sha1')
    return x, pk
Esempio n. 46
0
def generate_rsa_key_bio(bio, bits=2048, exponent=65537):
    """ Generates a 2048 RSA key to the file.    
     Use 65537 as default since the use of 3 might have some weaknesses"""

    def callback(*args):
        pass

    keypair = RSA.gen_key(bits, exponent, callback)
    keypair.save_key_bio(bio, None)
Esempio n. 47
0
 def test_pem(self):
     rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
     pkey = EVP.PKey()
     pkey.assign_rsa(rsa)
     self.assertNotEqual(pkey.as_pem(callback=self._pass_callback),
                         pkey.as_pem(cipher=None))
     with self.assertRaises(ValueError):
         pkey.as_pem(cipher='noXX$$%%suchcipher',
                     callback=self._pass_callback)
Esempio n. 48
0
 def _generate_new_key(self):
     if self._using_m2crypto:
         self._private_key = M2RSA.gen_key(2048, 65537, lambda x,y,z: None)
         self._public_key = M2RSA.RSA_pub(self._private_key.rsa)
     else:
         try:
             (self._public_key, self._private_key) = PYRSA.newkeys(2048, poolsize=4)
         except:
             (self._public_key, self._private_key) = PYRSA.newkeys(2048)
Esempio n. 49
0
def make_proxy_request(bits, subject):
    pk = EVP.PKey()
    x = X509.Request()
    rsa = RSA.gen_key(bits, 65537, lambda: None)
    pk.assign_rsa(rsa)
    x.set_pubkey(pk)
    x.set_subject(subject)
    x.sign(pk,'sha1')
    return x, pk
Esempio n. 50
0
    def test_get_modulus(self):
        pkey = EVP.PKey()
        self.assertRaises(ValueError, pkey.get_modulus)

        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        pkey.assign_rsa(rsa)
        mod = pkey.get_modulus()
        assert len(mod) > 0, mod
        assert len(mod.strip('0123456789ABCDEF')) == 0
Esempio n. 51
0
def generate_keys(passphrase, length=512, user=None):
    ciph, cb = quiet_passphrase(passphrase)
    keys = RSA.gen_key(length, 0x10001, callback=quiet_callback)
    bio = BIO.MemoryBuffer()
    keys.save_pub_key_bio(bio)
    public = bio.read()
    keys.save_key_bio(bio, cipher=ciph, callback=cb)
    private = bio.read()
    return public, private
Esempio n. 52
0
 def _generate_new_key(self):
     if self._using_m2crypto:
         self._private_key = M2RSA.gen_key(2048, 65537, lambda x,y,z: None)
         self._public_key = M2RSA.RSA_pub(self._private_key.rsa)
     else:
         try:
             (self._public_key, self._private_key) = PYRSA.newkeys(2048, poolsize=4)
         except:
             (self._public_key, self._private_key) = PYRSA.newkeys(2048)
Esempio n. 53
0
    def test_get_modulus(self):
        pkey = EVP.PKey()
        self.assertRaises(ValueError, pkey.get_modulus)

        rsa = RSA.gen_key(512, 3, callback=self._gen_callback)
        pkey.assign_rsa(rsa)
        mod = pkey.get_modulus()
        assert len(mod) > 0, mod
        assert len(mod.strip('0123456789ABCDEF')) == 0
Esempio n. 54
0
def make_key_pair(key_length=2048):
    "Make public/private keys"
    Rand.rand_seed(os.urandom(key_length))
    key = RSA.gen_key(key_length, 65537, blank_callback)
    pri_mem = BIO.MemoryBuffer()
    pub_mem = BIO.MemoryBuffer()
    key.save_key_bio(pri_mem, None)
    key.save_pub_key_bio(pub_mem)
    return pub_mem.getvalue(), pri_mem.getvalue()
Esempio n. 55
0
def genkeypair():
    from M2Crypto import RSA, BIO
    new_key = RSA.gen_key(1024, 65537)
    memory = BIO.MemoryBuffer()
    new_key.save_key_bio(memory, cipher=None)
    private_key = memory.getvalue()
    new_key.save_pub_key_bio(memory)
    pub_key = memory.getvalue()
    certs = {'privkey': private_key, 'pubkey': pub_key}
    return certs
def rsa_generate_keypair():
    """ Create keypair using default params, use __init__(keypair) parameter
    if you want to use custom params.
    """
    # Choose fast exponent e. See Handbook of applied cryptography $8.2.2(ii)
    # And small keysize, attackers have duration of broadcast to reverse
    # engineer key.
    e = 3
    keysize = 768
    return RSA.gen_key(keysize, e)
Esempio n. 57
0
    def test_get_modulus(self):
        pkey = EVP.PKey()
        with self.assertRaises(ValueError):
            pkey.get_modulus()

        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        pkey.assign_rsa(rsa)
        mod = pkey.get_modulus()
        self.assertGreater(len(mod), 0, mod)
        self.assertEqual(len(mod.strip(b'0123456789ABCDEF')), 0)
Esempio n. 58
0
 def _genCsr(self):
     rsa = RSA.gen_key(self._key_size, 65537)
     rsapem = rsa.as_pem(cipher=None)
     evp = EVP.PKey()
     evp.assign_rsa(rsa)
     rsa = None  # should not be freed here
     csr = X509.Request()
     csr.set_pubkey(evp)
     csr.sign(evp, 'sha1')
     return rsapem, csr.as_pem(), csr.get_pubkey().as_pem(cipher=None)
Esempio n. 59
0
 def test_pem(self):
     rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
     pkey = EVP.PKey()
     pkey.assign_rsa(rsa)
     assert pkey.as_pem(callback=self._pass_callback) != pkey.as_pem(
         cipher=None)
     self.assertRaises(ValueError,
                       pkey.as_pem,
                       cipher='noXX$$%%suchcipher',
                       callback=self._pass_callback)