Esempio n. 1
0
def getRSAKeys():
    public_key = os.path.join(SSH_PATH, 'id_rsa.pub')
    private_key = os.path.join(SSH_PATH, 'id_rsa')

    if not (os.path.exists(public_key) and os.path.exists(private_key)):
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.backends import default_backend
        KEY_LENGTH = 2048
        rsaKey = rsa.generate_private_key(public_exponent=65537,
                                          key_size=KEY_LENGTH,
                                          backend=default_backend())
        publicKeyString = keys.Key(rsaKey).public().toString('openssh')
        privateKeyString = keys.Key(rsaKey).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
Esempio n. 2
0
    def test_blobDSA(self):
        """
        Return the over-the-wire SSH format of the DSA public key.
        """
        publicNumbers = self.dsaObj.private_numbers().public_numbers

        self.assertEqual(
            keys.Key(self.dsaObj).blob(),
            common.NS(b'ssh-dss') +
            common.MP(publicNumbers.parameter_numbers.p) +
            common.MP(publicNumbers.parameter_numbers.q) +
            common.MP(publicNumbers.parameter_numbers.g) +
            common.MP(publicNumbers.y)
            )
Esempio n. 3
0
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 = 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)
        print "Done."
    else:
        with file(public_key) as f:
            publicKeyString = f.read()
        with file(private_key) as f:
            privateKeyString = f.read()
    return publicKeyString, privateKeyString
Esempio n. 4
0
def getRSAKeys():
    publicKeyFile: str = CowrieConfig.get("ssh", "rsa_public_key")
    privateKeyFile: str = CowrieConfig.get("ssh", "rsa_private_key")
    if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
        log.msg("Generating new RSA keypair...")
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import rsa

        rsaKey = rsa.generate_private_key(
            public_exponent=65537, key_size=2048, backend=default_backend()
        )
        publicKeyString = keys.Key(rsaKey).public().toString("openssh")
        privateKeyString = keys.Key(rsaKey).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, "rb") as f:
            publicKeyString = f.read()
        with open(privateKeyFile, "rb") as f:
            privateKeyString = f.read()
    return publicKeyString, privateKeyString
Esempio n. 5
0
def getDSAKeys():
    """
    """
    publicKeyFile = CONFIG.get('ssh', 'dsa_public_key')
    privateKeyFile = CONFIG.get('ssh', 'dsa_private_key')
    if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
        log.msg("Generating new DSA keypair...")
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import dsa
        dsaKey = dsa.generate_private_key(key_size=1024,
                                          backend=default_backend())
        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
Esempio n. 6
0
    def test_blobEC(self):
        """
        Return the over-the-wire SSH format of the EC public key.
        """
        from cryptography import utils

        byteLength = (self.ecObj.curve.key_size + 7) // 8
        self.assertEqual(
            keys.Key(self.ecObj).blob(),
            common.NS(keydata.ECDatanistp256['curve']) +
            common.NS(keydata.ECDatanistp256['curve'][-8:]) + common.
            NS(b'\x04' + utils.int_to_bytes(
                self.ecObj.private_numbers().public_numbers.x, byteLength) +
               utils.int_to_bytes(
                   self.ecObj.private_numbers().public_numbers.y, byteLength)))
Esempio n. 7
0
def generateECDSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import ec

    if not options['bits']:
        options['bits'] = 256
    # OpenSSH supports only mandatory sections of RFC5656.
    # See https://www.openssh.com/txt/release-5.7
    curve  = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii')
    keyPrimitive = ec.generate_private_key(
        curve=keys._curveTable[curve],
        backend=default_backend()
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options)
Esempio n. 8
0
    def test_privateBlobDSA(self):
        """
        L{keys.Key.privateBlob} returns the SSH protocol-level format of a DSA
        private key.
        """
        publicNumbers = self.dsaObj.private_numbers().public_numbers

        self.assertEqual(
            keys.Key(self.dsaObj).privateBlob(),
            common.NS(b'ssh-dss') +
            common.MP(publicNumbers.parameter_numbers.p) +
            common.MP(publicNumbers.parameter_numbers.q) +
            common.MP(publicNumbers.parameter_numbers.g) +
            common.MP(publicNumbers.y) +
            common.MP(self.dsaObj.private_numbers().x))
Esempio n. 9
0
def GenerateNewKey(keyfilename=None):
    global _MyKeyObject
    global _MyRsaKey
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    lg.out(4, 'key.InitMyKey generate new private key')
    _MyRsaKey = RSA.generate(settings.getPrivateKeySize(), os.urandom)
    _MyKeyObject = keys.Key(_MyRsaKey)
    keystring = _MyKeyObject.toString('openssh')
    bpio.WriteFile(keyfilename, keystring)
    lg.out(4, '    wrote %d bytes to %s' % (len(keystring), keyfilename))
Esempio n. 10
0
def getRSAKeys(cfg):
    """
    """
    publicKeyFile = cfg.get('ssh', 'rsa_public_key')
    privateKeyFile = cfg.get('ssh', 'rsa_private_key')
    if not (os.path.exists(publicKeyFile) and os.path.exists(privateKeyFile)):
        log.msg("Generating new RSA keypair...")
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import rsa
        rsaKey = rsa.generate_private_key(public_exponent=65537,
                                          key_size=2048,
                                          backend=default_backend())
        publicKeyString = keys.Key(rsaKey).public().toString('openssh')
        privateKeyString = keys.Key(rsaKey).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, 'rb') as f:
            publicKeyString = f.read()
        with open(privateKeyFile, 'rb') as f:
            privateKeyString = f.read()
    return publicKeyString, privateKeyString
Esempio n. 11
0
 def test_privateBlobEC(self):
     """
     L{keys.Key.privateBlob} returns the SSH ptotocol-level format of EC
     private key.
     """
     from cryptography.hazmat.primitives import serialization
     self.assertEqual(
         keys.Key(self.ecObj).privateBlob(),
         common.NS(keydata.ECDatanistp256['curve']) +
         common.NS(keydata.ECDatanistp256['curve'][-8:]) +
         common.NS(
             self.ecObj.public_key().public_bytes(
                 serialization.Encoding.X962,
                 serialization.PublicFormat.UncompressedPoint)) +
         common.MP(self.ecObj.private_numbers().private_value)
         )
Esempio n. 12
0
 def test_privateBlobRSA(self):
     """
     L{keys.Key.privateBlob} returns the SSH protocol-level format of an
     RSA private key.
     """
     numbers = self.rsaObj.private_numbers()
     self.assertEqual(
         keys.Key(self.rsaObj).privateBlob(),
         common.NS(b'ssh-rsa') +
         common.MP(numbers.public_numbers.n) +
         common.MP(numbers.public_numbers.e) +
         common.MP(numbers.d) +
         common.MP(numbers.iqmp) +
         common.MP(numbers.p) +
         common.MP(numbers.q)
         )
Esempio n. 13
0
 def test_privateBlobRSA(self):
     """
     L{keys.Key.privateBlob} returns the SSH protocol-level format of an
     RSA private key.
     """
     from cryptography.hazmat.primitives.asymmetric import rsa
     numbers = self.rsaObj.private_numbers()
     u = rsa.rsa_crt_iqmp(numbers.q, numbers.p)
     self.assertEqual(
         keys.Key(self.rsaObj).privateBlob(),
         common.NS(b'ssh-rsa') +
         common.MP(self.rsaObj.private_numbers().public_numbers.n) +
         common.MP(self.rsaObj.private_numbers().public_numbers.e) +
         common.MP(self.rsaObj.private_numbers().d) + common.MP(u) +
         common.MP(self.rsaObj.private_numbers().p) +
         common.MP(self.rsaObj.private_numbers().q))
Esempio n. 14
0
    def test_reprPrivateECDSA(self):
        """
        The repr of a L{keys.Key} contains all the OpenSSH format for an ECDSA
        private key.
        """
        self.assertEqual(repr(keys.Key(self.ecObj)),
"""<Elliptic Curve Private Key (256 bits)
curve:
\tecdsa-sha2-nistp256
privateValue:
\t34638743477210341700964008455655698253555655678826059678074967909361042656500
x:
\t76282513020392096317118503144964731774299773481750550543382904345687059013883
y:""" +
"\n\t8154319786460285263226566476944164753434437589431431968106113715931064" +
"6683104>\n")
Esempio n. 15
0
def changePassPhrase(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input(
            'Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename']).keyObject
    except keys.EncryptedKeyError as e:
        # Raised if password not supplied for an encrypted key
        if not options.get('pass'):
            options['pass'] = getpass.getpass('Enter old passphrase: ')
        try:
            key = keys.Key.fromFile(
                options['filename'], passphrase=options['pass']).keyObject
        except keys.BadKeyError:
            sys.exit('Could not change passphrase: old passphrase error')
        except keys.EncryptedKeyError as e:
            sys.exit('Could not change passphrase: %s' % (e,))
    except keys.BadKeyError as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    if not options.get('newpass'):
        while 1:
            p1 = getpass.getpass(
                'Enter new passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print 'Passphrases do not match.  Try again.'
        options['newpass'] = p1

    try:
        newkeydata = keys.Key(key).toString('openssh',
                                            extra=options['newpass'])
    except Exception as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    try:
        keys.Key.fromString(newkeydata, passphrase=options['newpass'])
    except (keys.EncryptedKeyError, keys.BadKeyError) as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    fd = open(options['filename'], 'w')
    fd.write(newkeydata)
    fd.close()

    print 'Your identification has been saved with the new passphrase.'
Esempio n. 16
0
 def test_fromStringErrors(self):
     """
     keys.Key.fromString should raise BadKeyError when the key is invalid.
     """
     self.assertRaises(keys.BadKeyError, keys.Key.fromString, '')
     # no key data with a bad key type
     self.assertRaises(keys.BadKeyError, keys.Key.fromString, '',
             'bad_type')
     # trying to decrypt a key which doesn't support encryption
     self.assertRaises(keys.BadKeyError, keys.Key.fromString,
             keydata.publicRSA_lsh, passphrase = 'unencrypted')
     # trying to decrypt an unencrypted key
     self.assertRaises(keys.EncryptedKeyError, keys.Key.fromString,
             keys.Key(self.rsaObj).toString('openssh', 'encrypted'))
     # key with no key data
     self.assertRaises(keys.BadKeyError, keys.Key.fromString,
             '-----BEGIN RSA KEY-----\nwA==\n')
Esempio n. 17
0
    def test_reprPublicRSA(self):
        """
        The repr of a L{keys.Key} contains all of the RSA components for an RSA
        public key.
        """
        self.assertEqual(
            repr(keys.Key(self.rsaObj).public()), """<RSA Public Key (768 bits)
attr e:
\t23
attr n:
\t00:af:32:71:f0:e6:0e:9c:99:b3:7f:8b:5f:04:4b:
\tcb:8b:c0:d5:3e:b2:77:fd:cf:64:d8:8f:c0:cf:ae:
\t1f:c6:31:df:f6:29:b2:44:96:e2:c6:d4:21:94:7f:
\t65:7c:d8:d4:23:1f:b8:2e:6a:c9:1f:94:0d:46:c1:
\t69:a2:b7:07:0c:a3:93:c1:34:d8:2e:1e:4a:99:1a:
\t6c:96:46:07:46:2b:dc:25:29:1b:87:f0:be:05:1d:
\tee:b4:34:b9:e7:99:95>""")
Esempio n. 18
0
    def test_repr(self):
        """
        Test the pretty representation of Key.
        """
        self.assertEqual(
            repr(keys.Key(self.rsaObj)), """<RSA Private Key (0 bits)
attr d:
\t03
attr e:
\t02
attr n:
\t01
attr p:
\t04
attr q:
\t05
attr u:
\t04>""")
Esempio n. 19
0
 def testMultipleFactories(self):
     f1 = factory.SSHFactory()
     f2 = factory.SSHFactory()
     gpk = lambda: {'ssh-rsa': keys.Key(None)}
     f1.getPrimes = lambda: None
     f2.getPrimes = lambda: {1: (2, 3)}
     f1.getPublicKeys = f2.getPublicKeys = gpk
     f1.getPrivateKeys = f2.getPrivateKeys = gpk
     f1.startFactory()
     f2.startFactory()
     p1 = f1.buildProtocol(None)
     p2 = f2.buildProtocol(None)
     self.failIf(
         'diffie-hellman-group-exchange-sha1' in p1.supportedKeyExchanges,
         p1.supportedKeyExchanges)
     self.failUnless(
         'diffie-hellman-group-exchange-sha1' in p2.supportedKeyExchanges,
         p2.supportedKeyExchanges)
Esempio n. 20
0
    def _cbSignData(self, privateKey, signData):
        """
        Called back when the private key is returned.  Sign the data and
        return the signature.

        @param privateKey: the private key object
        @type publicKey: L{keys.Key}
        @param signData: the data to be signed by the private key.
        @type signData: C{str}
        @return: the signature
        @rtype: C{str}
        """
        if not isinstance(privateKey, keys.Key):
            warnings.warn("Returning a PyCrypto key object from "
                          "SSHUserAuthClient.getPrivateKey() is deprecated "
                          "since Twisted 9.0.  Return a keys.Key() instead.",
                          DeprecationWarning)
            privateKey = keys.Key(privateKey)
        return privateKey.sign(signData)
Esempio n. 21
0
def main():
    log.startLogging(sys.stderr)

    keylocation = os.path.expanduser(
        os.path.join('~', '.gitserverglue', 'key.pem'))
    key = None

    if os.path.exists(keylocation):
        try:
            key = keys.Key.fromFile(keylocation)
        except:
            pass

    if key is None:
        rsakey = RSA.generate(2048)
        key = keys.Key(rsakey)

        try:
            if not os.path.exists(os.path.dirname(keylocation)):
                os.mkdir(os.path.dirname(keylocation))
            f = open(keylocation, 'wb')
            f.write(rsakey.exportKey('PEM'))
            f.close()
        except:
            log.err(None, "Failed to write key to " + keylocation)

    ssh_factory = ssh.create_factory(public_keys={'ssh-rsa': key},
                                     private_keys={'ssh-rsa': key},
                                     authnz=TestAuthnz(),
                                     git_configuration=TestGitConfiguration())

    http_factory = http.create_factory(
        authnz=TestAuthnz(),
        git_configuration=TestGitConfiguration(),
        git_viewer=find_git_viewer())

    git_factory = git.create_factory(authnz=TestAuthnz(),
                                     git_configuration=TestGitConfiguration())

    reactor.listenTCP(5522, ssh_factory)
    reactor.listenTCP(8080, make_site_streaming(http_factory))
    reactor.listenTCP(9418, git_factory)
    reactor.run()
Esempio n. 22
0
def generate_key(key_id,
                 key_size=4096,
                 keys_folder=None,
                 output_type='openssh'):
    """
    """
    if key_id in known_keys():
        lg.warn('key "%s" already exists' % key_id)
        return None
    lg.out(4, 'my_keys.generate_key "%s" of %d bits' % (key_id, key_size))
    rsa_key = RSA.generate(key_size, os.urandom)
    key_object = keys.Key(rsa_key)
    known_keys()[key_id] = key_object
    if not keys_folder:
        keys_folder = settings.PrivateKeysDir()
    key_string = key_object.toString(output_type)
    key_filepath = os.path.join(keys_folder, key_id)
    bpio.WriteFile(key_filepath, key_string)
    if _Debug:
        lg.out(_DebugLevel, '    key %s saved to %s' % (key_id, key_filepath))
    return key_object
Esempio n. 23
0
    def test_reprPrivateRSA(self):
        """
        The repr of a L{keys.Key} contains all of the RSA components for an RSA
        private key.
        """
        self.assertEqual(
            repr(keys.Key(self.rsaObj)), """<RSA Private Key (768 bits)
attr d:
\t6e:1f:b5:55:97:eb:ed:67:ed:2b:99:6e:ec:c1:ed:
\ta8:4d:52:d6:f3:d6:65:06:04:df:e5:54:9f:cc:89:
\t00:3c:9b:67:87:ec:65:a0:ab:cd:6f:65:90:8a:97:
\t90:4d:c6:21:8f:a8:8d:d8:59:86:43:b5:81:b1:b4:
\td7:5f:2c:22:0a:61:c1:25:8a:47:12:b4:9a:f8:7a:
\t11:1c:4a:a8:8b:75:c4:91:09:3b:be:04:ca:45:d9:
\t57:8a:0d:27:cb:23
attr e:
\t23
attr n:
\t00:af:32:71:f0:e6:0e:9c:99:b3:7f:8b:5f:04:4b:
\tcb:8b:c0:d5:3e:b2:77:fd:cf:64:d8:8f:c0:cf:ae:
\t1f:c6:31:df:f6:29:b2:44:96:e2:c6:d4:21:94:7f:
\t65:7c:d8:d4:23:1f:b8:2e:6a:c9:1f:94:0d:46:c1:
\t69:a2:b7:07:0c:a3:93:c1:34:d8:2e:1e:4a:99:1a:
\t6c:96:46:07:46:2b:dc:25:29:1b:87:f0:be:05:1d:
\tee:b4:34:b9:e7:99:95
attr p:
\t00:cb:4a:4b:d0:40:47:e8:45:52:f7:c7:af:0c:20:
\t6d:43:0d:b6:39:94:f9:da:a5:e5:03:06:76:83:24:
\teb:88:a1:55:a2:a8:de:12:3b:77:49:92:8a:a9:71:
\td2:02:93:ff
attr q:
\t00:dc:9f:6b:d9:98:21:56:11:8d:e9:5f:03:9d:0a:
\td3:93:6e:13:77:41:3c:85:4f:00:70:fd:05:54:ff:
\tbc:3d:09:bf:83:f6:97:7f:64:10:91:04:fe:a2:67:
\t47:54:42:6b
attr u:
\t00:b4:73:97:4b:50:10:a3:17:b3:a8:47:f1:3a:14:
\t76:52:d1:38:2a:cf:12:14:34:c1:a8:54:4c:29:35:
\t80:a0:38:b8:f0:fa:4c:c4:c2:85:ab:db:87:82:ba:
\tdc:eb:db:2a>""")
Esempio n. 24
0
File: ckeygen.py Progetto: DT021/wau
def _saveKey(key, options):
    if not options['filename']:
        kind = keys.objectType(key)
        kind = {'ssh-rsa': 'rsa', 'ssh-dss': 'dsa'}[kind]
        filename = os.path.expanduser('~/.ssh/id_%s' % kind)
        options['filename'] = raw_input(
            'Enter file in which to save the key (%s): ' %
            filename).strip() or filename
    if os.path.exists(options['filename']):
        print '%s already exists.' % options['filename']
        yn = raw_input('Overwrite (y/n)? ')
        if yn[0].lower() != 'y':
            sys.exit()
    if options.get('no-passphrase'):
        options['pass'] = b''
    elif not options['pass']:
        while 1:
            p1 = getpass.getpass(
                'Enter passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print 'Passphrases do not match.  Try again.'
        options['pass'] = p1

    keyObj = keys.Key(key)
    comment = '%s@%s' % (getpass.getuser(), socket.gethostname())

    filepath.FilePath(options['filename']).setContent(
        keyObj.toString('openssh', options['pass']))
    os.chmod(options['filename'], 33152)

    filepath.FilePath(options['filename'] + '.pub').setContent(
        keyObj.public().toString('openssh', comment))

    print 'Your identification has been saved in %s' % options['filename']
    print 'Your public key has been saved in %s.pub' % options['filename']
    print 'The key fingerprint is:'
    print keyObj.fingerprint()
Esempio n. 25
0
    def test_fromStringErrors(self):
        """
        keys.Key.fromString should raise BadKeyError when the key is invalid.
        """
        self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'')
        # no key data with a bad key type
        self.assertRaises(keys.BadKeyError, keys.Key.fromString, b'',
                          'bad_type')
        # trying to decrypt a key which doesn't support encryption
        self.assertRaises(keys.BadKeyError,
                          keys.Key.fromString,
                          keydata.publicRSA_lsh,
                          passphrase=b'unencrypted')
        # trying to decrypt a key with the wrong passphrase
        self.assertRaises(
            keys.EncryptedKeyError, keys.Key.fromString,
            keys.Key(self.rsaObj).toString('openssh', b'encrypted'))
        # key with no key data
        self.assertRaises(keys.BadKeyError, keys.Key.fromString,
                          b'-----BEGIN RSA KEY-----\nwA==\n')
        # key with invalid DEK Info
        self.assertRaises(keys.BadKeyError,
                          keys.Key.fromString,
                          b"""-----BEGIN ENCRYPTED RSA KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: weird type

4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB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ARO5bjcWKSZeN/Ybgk
gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
-----END RSA PRIVATE KEY-----""",
                          passphrase='encrypted')
        # key with invalid encryption type
        self.assertRaises(keys.BadKeyError,
                          keys.Key.fromString,
                          b"""-----BEGIN ENCRYPTED RSA KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: FOO-123-BAR,01234567

4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC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-----""",
                          passphrase='encrypted')
        # key with bad IV (AES)
        self.assertRaises(keys.BadKeyError,
                          keys.Key.fromString,
                          b"""-----BEGIN ENCRYPTED RSA KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,01234

4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
-----END RSA PRIVATE KEY-----""",
                          passphrase='encrypted')
        # key with bad IV (DES3)
        self.assertRaises(keys.BadKeyError,
                          keys.Key.fromString,
                          b"""-----BEGIN ENCRYPTED RSA KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,01234

4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
sXrfpYc6TJtOQlHd/52JB6aA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cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
-----END RSA PRIVATE KEY-----""",
                          passphrase='encrypted')
Esempio n. 26
0
 def test_toStringErrors(self):
     """
     Test that toString raises errors appropriately.
     """
     self.assertRaises(keys.BadKeyError,
                       keys.Key(self.rsaObj).toString, 'bad_type')
Esempio n. 27
0
        else:
            if not options['pass']:
                options['pass'] = getpass.getpass('Enter old passphrase: ')
            key = keys.Key.fromFile(options['filename'],
                                    passphrase=options['pass']).keyObject
    if not options['newpass']:
        while 1:
            p1 = getpass.getpass(
                'Enter new passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print 'Passphrases do not match.  Try again.'
        options['newpass'] = p1
    open(options['filename'],
         'w').write(keys.Key(key).toString(passphrase=options['newpass']))
    print 'Your identification has been saved with the new passphrase.'


def displayPublicKey(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input(
            'Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename']).keyObject
    except keys.BadKeyError, e:
        if e.args[0] != 'encrypted key with no passphrase':
            raise
        else:
            if not options['pass']:
Esempio n. 28
0
def generateEd25519key(options):
    from cryptography.hazmat.primitives.asymmetric import ed25519

    keyPrimitive = ed25519.Ed25519PrivateKey.generate()
    key = keys.Key(keyPrimitive)
    _saveKey(key, options)
Esempio n. 29
0
 def test_dataError(self):
     """
     The L{keys.Key.data} method raises RuntimeError for bad keys.
     """
     badKey = keys.Key(b'')
     self.assertRaises(RuntimeError, badKey.data)
Esempio n. 30
0
    def test_reprPrivateRSA(self):
        """
        The repr of a L{keys.Key} contains all of the RSA components for an RSA
        private key.
        """
        self.assertEqual(repr(keys.Key(self.rsaObj)),
"""<RSA Private Key (2048 bits)
attr d:
\t21:4c:08:66:a2:28:d5:b4:fb:8e:0f:72:1b:85:09:
\t00:b9:f2:4e:37:f0:1c:57:4b:e3:51:7f:9e:23:a7:
\te4:3a:98:55:1b:ea:8b:7a:98:1e:bc:d8:ba:b1:f9:
\t89:12:18:60:ac:e8:cc:0b:4e:09:5a:40:6a:ba:2f:
\t99:f8:b3:24:60:84:b9:ce:69:95:9a:f9:e2:fc:1f:
\t51:4d:27:15:db:2b:27:ad:ef:b4:69:ac:be:7d:10:
\teb:86:47:70:73:b4:00:87:95:15:3b:37:f9:e7:14:
\te7:80:bb:68:1e:1b:e6:dd:bb:73:63:b9:67:e6:b2:
\t27:7f:cf:cf:30:9b:c2:98:fd:d9:18:36:2f:36:2e:
\tf1:3d:81:7a:9f:e1:03:2d:47:db:34:51:62:39:dd:
\t4f:e9:ac:a8:8b:d9:d6:f3:84:c4:17:b9:71:9d:06:
\t08:42:78:4d:bb:c5:2a:f4:c3:58:cd:55:2b:ed:be:
\t33:5f:04:ea:7b:e6:04:24:63:f2:2d:d7:3d:1b:6c:
\td5:9c:63:43:2f:92:88:8d:3e:6e:da:18:37:d8:0f:
\t25:67:89:1d:b9:46:34:5e:c9:ce:c4:8b:ed:92:5a:
\t33:07:0f:df:86:08:f9:92:e9:db:eb:38:08:36:c9:
\tcd:cd:0a:01:48:5b:39:3e:7a:ca:c6:80:a9:dc:d4:
\t39
attr e:
\t01:00:01
attr n:
\t00:d5:6a:ac:78:23:d6:d6:1b:ec:25:a1:50:c4:77:
\t63:50:84:45:01:55:42:14:2a:2a:e0:d0:60:ee:d4:
\te9:a3:ad:4a:fa:39:06:5e:84:55:75:5f:00:36:bf:
\t6f:aa:2a:3f:83:26:37:c1:69:2e:5b:fd:f0:f3:d2:
\t7d:d6:98:cd:3a:40:78:d5:ca:a8:18:c0:11:93:24:
\t09:0c:81:4c:8f:f7:9c:ed:13:16:6a:a4:04:e9:49:
\t77:c3:e4:55:64:b3:79:68:9e:2c:08:eb:ac:e8:04:
\t2d:21:77:05:a7:8e:ef:53:30:0d:a5:e5:bb:3d:6a:
\te2:09:36:6f:fd:34:d3:7d:6f:46:ff:87:da:a9:29:
\t27:aa:ff:ad:f5:85:e6:3e:1a:b8:7a:1d:4a:b1:ea:
\tc0:5a:f7:30:df:1f:c2:a4:e4:ef:3f:91:49:96:40:
\td5:19:77:2d:37:c3:5e:ec:9d:a6:3a:44:a5:c2:a4:
\t29:dd:d5:ba:9c:3d:45:b3:c6:2c:18:64:d5:ba:3d:
\tdf:ab:7f:cd:42:ac:a7:f1:18:0b:a0:58:15:62:0b:
\ta4:2a:6e:43:c3:e4:04:9f:35:a3:47:8e:46:ed:33:
\ta5:65:bd:bc:3b:29:6e:02:0b:57:df:74:e8:13:b4:
\t37:35:7e:83:5f:20:26:60:a6:dc:ad:8b:c6:6c:79:
\t98:f7
attr p:
\t00:d9:70:06:d8:e2:bc:d4:78:91:50:94:d4:c1:1b:
\t89:38:6c:46:64:5a:51:a0:9a:07:3d:48:8f:03:51:
\tcc:6b:12:8e:7d:1a:b1:65:e7:71:75:39:e0:32:05:
\t75:8d:18:4c:af:93:b1:49:b1:66:5f:78:62:7a:d1:
\t0c:ca:e6:4d:43:b3:9c:f4:6b:7d:e6:0c:98:dc:cf:
\t21:62:8e:d5:2e:12:de:04:ae:d7:24:6e:83:31:a2:
\t15:a2:44:3d:22:a9:62:26:22:b9:b2:ed:54:0a:9d:
\t08:83:a7:07:0d:ff:19:18:8e:d8:ab:1d:da:48:9c:
\t31:68:11:a1:66:6d:e3:d8:1d
attr q:
\t00:fb:44:17:8b:a4:36:be:1e:37:1d:a7:f6:61:6c:
\t04:c4:aa:dd:78:3e:07:8c:1e:33:02:ae:03:14:87:
\t83:7a:e5:9e:7d:08:67:a8:f2:aa:bf:12:70:cf:72:
\ta9:a7:c7:0b:1d:88:d5:20:fd:9c:63:ca:47:30:55:
\t4e:8b:c4:cf:f4:7f:16:a4:92:12:74:a1:09:c2:c4:
\t6e:9c:8c:33:ef:a5:e5:f7:e0:2b:ad:4f:5c:11:aa:
\t1a:84:37:5b:fd:7a:ea:c3:cd:7c:b0:c8:e4:1f:54:
\t63:b5:c7:af:df:f4:09:a7:fc:c7:25:fc:5c:e9:91:
\td7:92:c5:98:1e:56:d3:b1:23
attr u:
\t00:85:4b:1b:7a:9b:12:10:37:9e:1f:ad:5e:da:fe:
\tc6:96:fe:df:35:6b:b9:34:e2:16:97:92:26:09:bd:
\tbd:70:20:03:a7:35:bd:2d:1b:a0:d2:07:47:2b:d4:
\tde:a8:a8:07:07:1b:b8:04:20:a7:27:41:3c:6c:39:
\t39:e9:41:ce:e7:17:1d:d1:4c:5c:bc:3d:d2:26:26:
\tfe:6a:d6:fd:48:72:ae:46:fa:7b:c3:d3:19:60:44:
\t1d:a5:13:a7:80:f5:63:29:d4:7a:5d:06:07:16:5d:
\tf6:8b:3d:cb:64:3a:e2:84:5a:4d:8c:06:2d:2d:9d:
\t1c:eb:83:4c:78:3d:79:54:ce>""")