Пример #1
0
    def __init__( self, **kw ):
        """ Constructor, kw is dict of CRT paramters and RSA key.
Required RSA priv. key params (as long)
 n, d, e - modulus and private exponent
or
 p, q, e - primes p, q, and public exponent e
If also dp, dq, qinv present, they are checked to be consistent.
Default value for e is 0x10001
"""
#        super( RSAtoken, self ).__init__( **kw )
        Token.__init__( self, **kw )
        # check RSA parameters
        for par in ( 'n', 'd', 'e', 'p', 'q', 'dp', 'dq', 'dqinv' ):
            if par in kw:
                assert isinstance( long( kw[par] ), long ), \
                    "RSA parameter %s must be long" % par
        e = long( kw.get( 'e', 0x10001L ))
        if 'n' in kw and 'd' in kw:
            self.key = RSA.construct(( n, e, d ))
        elif 'p' in kw and 'q' in kw:
            p = kw['p']
            q = kw['q']
            n = p*q
            d = number.inverse( e, (p-1)*(q-1))
            if 'd' in kw:
                assert d == kw['d'], "Inconsinstent private exponent"
            if 'dp' in kw:
                assert d % (p-1) == kw['dp'], "Inconsistent d mod (p-1)"
            if 'dq' in kw:
                assert d % (q-1) == kw['dq'], "Inconsistent d mod (q-1)"
            u = number.inverse( q, p )
            if 'qinv' in kw:
                assert u == kw['qinv'], "Inconsistent q inv"
            self.key = RSA.construct(( n, e, d, q, p, u ))
Пример #2
0
def share_directory(other_username, dlog):
    with open(dlog, 'rb') as input:
        log = pickle.load(input)

    userList = log['users']
    userList.append(other_username)
    owner_block = log[owner]
    owner = log['owner']
    key = RSA.importKey(open(owner + '.pri').read())
    cipher = PKCS1_OAEP.new(key, SHA256.new())
    owner_block.decrypt_permission_block(cipher)
    file_aes_key = owner_block.get_file_encryption_key()
    file_dsa_key = None
    user_block = AccessBlock(file_aes_key, file_dsa_key)
    other_key = RSA.importKey(open(other_username + '.pub').read())
    other_cipher = PKCS1_OAEP.new(other_key, SHA256.new())
    user_block.encrypt_permission_block(other_cipher)
    log[other_username] = user_block
    file_log_hash = SHA256.new()
    with open(filelog, 'wb') as infile:
        pickle.dump(log, infile, -1)
    length = len(log)
    with open(filelog, 'rb') as outfile:
        picklelog = outfile.read(length)
    file_log_hash.update(picklelog)
    with open(owner + '.dsa', 'rb') as infile:
        owner_msk = pickle.load(infile)
    k = random.StrongRandom().randint(1,owner_msk.q-1)
    sig = owner_msk.sign(file_log_hash.digest(), k)
    with open(filelog, 'a+b') as outfile:
        pickle.dump(sig, outfile, -1)    
Пример #3
0
    def _real_auth(self):
        url = 'http://' + self.host + '/authenticate'
        rsakey = RSA.importKey(self.privkey, self.password)
        shibboleth = 'Mom sent me'
        signature = rsakey.sign(shibboleth, rng(384))[0]
        data = {'username': self.username, 
                'shibboleth': shibboleth, 
                'signature': str(signature)}

        r = requests.post(url, data=data)
        
        if r.status_code != 200:
            r.raise_for_status()

        if not r.cookies['signature']:
            raise SecurityException('Server did not return cookie.')

        servkey = self.get_pubkey('server')
        rsakey = RSA.importKey(servkey)
        servsig = int(r.cookies['signature'])

        if not rsakey.verify(self.username, (servsig,)):
            raise SecurityException('Could not verify server signature') 

        return r.cookies
Пример #4
0
    def test_sign(self):

        data = "Hello World!"
        for algorithm, hash_method in (
            ("rsa-sha1", hashlib.sha1,),
            ("rsa-sha256", hashlib.sha256,),
        ):
            stream = MemoryStream(data)
            headers = Headers()
            headers.addRawHeader("Originator", "mailto:user01@example.com")
            headers.addRawHeader("Recipient", "mailto:user02@example.com")
            headers.setHeader("Content-Type", MimeType("text", "calendar", **{"component": "VEVENT", "charset": "utf-8"}))
            request = DKIMRequest("POST", "/", headers, stream, "example.com", "dkim", self.private_keyfile, algorithm, ("Originator", "Recipient", "Content-Type",), True, True, True, 3600)
            result = (yield request.sign())

            # Manually create what should be the correct thing to sign and make sure signatures match
            bodyhash = base64.b64encode(hash_method(DKIMUtils.canonicalizeBody(data)).digest())
            sign_this = """originator:mailto:user01@example.com
recipient:mailto:user02@example.com
content-type:%s
ischedule-version:1.0
ischedule-message-id:%s
dkim-signature:v=1; d=example.com; s=dkim; t=%s; x=%s; a=%s; q=private-exchange:http/well-known:dns/txt; c=ischedule-relaxed/simple; h=Originator:Recipient:Content-Type:iSchedule-Version:iSchedule-Message-ID; bh=%s; b=""".replace("\n", "\r\n") % (headers.getRawHeaders("Content-Type")[0], request.message_id, request.time, request.expire, algorithm, bodyhash)
            key = RSA.importKey(open(self.private_keyfile).read())
            signature = DKIMUtils.sign(sign_this, key, DKIMUtils.hash_func(algorithm))

            self.assertEqual(result, signature)

            # Make sure header is updated in the request
            updated_header = "v=1; d=example.com; s=dkim; t=%s; x=%s; a=%s; q=private-exchange:http/well-known:dns/txt; c=ischedule-relaxed/simple; h=Originator:Recipient:Content-Type:iSchedule-Version:iSchedule-Message-ID; bh=%s; b=%s" % (request.time, request.expire, algorithm, bodyhash, signature,)
            self.assertEqual(request.headers.getRawHeaders("DKIM-Signature")[0], updated_header)

            # Try to verify result using public key
            pubkey = RSA.importKey(open(self.public_keyfile).read())
            self.assertEqual(DKIMUtils.verify(sign_this, result, pubkey, DKIMUtils.hash_func(algorithm)), None)
Пример #5
0
def generate_key_pair():
  # client = lib.transport.client()
  if(os.path.exists(lib.constants.m_private_key_file)):
    print("key file already present : {0}".format(lib.constants.m_private_key_file))
    f = open(lib.constants.m_private_key_file, "r")
    key = RSA.importKey(f.read())
    public_key = key.publickey().exportKey("PEM")
    lib.debug.debug(public_key)

  else:
    if(not os.path.exists(lib.constants.masterdir)):
      try:
        os.makedirs(lib.constants.masterdir)
      except:
        print (sys.exc_info())
    random_generator = Random.new().read
    key = RSA.generate(2048, random_generator)
    private_key_file = open(lib.constants.m_private_key_file, "w")
    private_key_file.write(key.exportKey("PEM"))
    private_key_file.flush()
    private_key_file.close()
    public_key = key.publickey().exportKey("PEM")
    lib.debug.debug(public_key)

  # client.send(message_type_args={lib.constants.msg_keys.tasktype:lib.constants.tasktypes.key_register,
  #                                lib.constants.msg_keys.payload :public_key,
  #
  #                                })
  print ("done writing private key")
Пример #6
0
 def keyFromString(key):
     """Creates a key object from a string representation"""
     if isinstance(key, str):
         return RSA.importKey(key)
     elif isinstance(key, bytes):
         return RSA.importKey(key.decode())
     return key
Пример #7
0
def fermat_factor_attack(ciphertexts):
   options = dict(feathermodules.current_options)
   options = prepare_options(options, ciphertexts)
   if options == False:
      print '[*] Could not process options.'
      return False
   answers = []
   for ciphertext in ciphertexts:
      try:
         key = RSA.importKey(ciphertext)
         if key.has_private():
            continue
         else:
            modulus = key.n
            exponent = key.e
      except:
         continue

      factors = ca.fermat_factor(modulus, minutes=options['minutes_to_wait'], verbose=True)
      if factors[0] != 1:
         answers.append( (modulus, exponent, ca.derive_d_from_pqe(factors[0],factors[1],exponent)) )
   
   for answer in answers:
      key = RSA.construct(answer)
      print "Found private key:\n%s" % key.exportKey()
   
   return ''
Пример #8
0
    def __init__(self, from_file=None, passphrase=None):
        if from_file == None:
            # generate a new pair
            rng = Random.new().read
            key = RSA.generate(4096 * 2, rng)
            self.public_key = IdentityPublicKey(key)
            self.private_key = IdentityPrivateKey(key)
        else:
            # read from file:
            f = open(from_file, "rb")
            contents = f.read(4096 * 1024)  # no more than 4mb
            f.close()
            key = RSA.importKey(contents.decode("utf-8", "ignore"),
                passphrase=passphrase)
            self.public_key = IdentityPublicKey(key)
            if key.has_private():
                self.private_key = IdentityPrivateKey(key)
            else:
                self.private_key = None

            # ensure the minimum required RSA key size is met:
            if self.public_key.size() < ENCRYPT_BIT_MINIMUM or (\
                    self.private_key != None and \
                    self.private_key.size() < ENCRYPT_BIT_MINIMUM):
                self.private_key = None
                self.public_key = None
                raise ValueError("this RSA key doesn't meet the required " +\
                    "minimum bit size for proper encryption")
        if self.private_key != None:
            self.cipher = PKCS1_OAEP.new(self.private_key.key,
                hashAlgo=SHA256)
        else:
            self.cipher = PKCS1_OAEP.new(self.public_key.key,
                hashAlgo=SHA256)
Пример #9
0
    def __init__(self, keyDer = None):
        # TODO: Implementation of managed properties?

        if keyDer == None:
            self._keyDer = Blob()
            self._keyType = None
            return

        self._keyDer = keyDer

        # Get the public key OID.
        oidString = ""
        try:
            parsedNode = DerNode.parse(keyDer.buf(), 0)
            rootChildren = parsedNode.getChildren()
            algorithmIdChildren = DerNode.getSequence(
              rootChildren, 0).getChildren()
            oidString = algorithmIdChildren[0].toVal()
        except DerDecodingException as ex:
          raise UnrecognizedKeyFormatException(
            "PublicKey.decodeKeyType: Error decoding the public key" + str(ex))

        # Verify that the we can decode.
        if oidString == self.RSA_ENCRYPTION_OID:
            self._keyType = KeyType.RSA
            RSA.importKey(keyDer.toRawStr())
        elif oidString == self.EC_ENCRYPTION_OID:
            self._keyType = KeyType.ECDSA
            # TODO: Check EC decoding.
        else:
            raise UnrecognizedKeyFormatException(
              "PublicKey.decodeKeyType: Unrecognized OID " + oidString)
Пример #10
0
    def test_encode_decode_with_rsa_sha512(self):
        try:
            from Crypto.PublicKey import RSA

            # PEM-formatted RSA key
            with open('tests/testkey_rsa', 'r') as rsa_priv_file:
                priv_rsakey = RSA.importKey(rsa_priv_file.read())
                jwt_message = jwt.encode(self.payload, priv_rsakey,
                                         algorithm='RS512')

            with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
                pub_rsakey = RSA.importKey(rsa_pub_file.read())
                assert jwt.decode(jwt_message, pub_rsakey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_rsakey, *load_output)

            # string-formatted key
            with open('tests/testkey_rsa', 'r') as rsa_priv_file:
                priv_rsakey = rsa_priv_file.read()
                jwt_message = jwt.encode(self.payload, priv_rsakey,
                                         algorithm='RS512')

            with open('tests/testkey_rsa.pub', 'r') as rsa_pub_file:
                pub_rsakey = rsa_pub_file.read()
                assert jwt.decode(jwt_message, pub_rsakey)

                load_output = jwt.load(jwt_message)
                jwt.verify_signature(key=pub_rsakey, *load_output)
        except ImportError:
            pass
Пример #11
0
def get_keypair(client_id):
    hash = SHA256.new(client_id).hexdigest()
    name = data_path + '/' + hash
    aes_key = SHA256.new(master_key+client_id).digest()
    aes = AES.new(aes_key, AES.MODE_CTR, counter=Counter.new(128))
    try:
        f = open(name)
        d1 = json.load(f)
        f.close()
        d2 = json.loads(aes.decrypt(b64decode(d1['data'].encode())).decode())
        rsa_key = RSA.construct((d2['n'], d2['e'],
                                 d2['d'], d2['p'], d2['q'], d2['u']))
    except:
        rsa_key = RSA.generate(1024)
        t = int(time())
        d2 = dict(id=hash,
                  client_id=client_id,
                  n=rsa_key.n, e=rsa_key.e,
                  d=rsa_key.d, p=rsa_key.p, q=rsa_key.q, u=rsa_key.u,
                  generated_at=t)
        d1 = dict(id=hash,
                  data=b64encode(aes.encrypt(json.dumps(d2))).decode(),
                  generated_at=t)
        f = open(name, 'w')
        json.dump(d1, f, sort_keys=True, indent=2)
        f.close()
    return rsa_key
Пример #12
0
 def test_handle_create_payload_calls_get_outbound_entity(self, mock_get_outbound_entity):
     mock_get_outbound_entity.return_value = DiasporaPost()
     from_user = Mock(private_key=RSA.generate(2048), handle="foobar@domain.tld")
     to_user = Mock(key=RSA.generate(2048).publickey())
     entity = DiasporaPost()
     handle_create_payload(from_user, to_user, entity)
     assert mock_get_outbound_entity.called
Пример #13
0
    def __init__(self, dir=None, key='', passphrase=None, cipher=utils.AESCipher):
        super(LocalRsaProvider, self).__init__(cipher=cipher)
        self.dir = dir or os.path.join(os.path.expanduser('~'), _LOCAL_RSA_TMP_DIR)

        utils.makedir_p(self.dir)

        priv_key_full_path = os.path.join(self.dir, key + self.PRIV_KEY_FILE)
        pub_key_full_path = os.path.join(self.dir, key + self.PUB_KEY_FILE)
        try:
            if os.path.exists(priv_key_full_path) and os.path.exists(pub_key_full_path):
                with open(priv_key_full_path, 'rb') as f:
                    self.__decrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase))

                with open(pub_key_full_path, 'rb') as f:
                    self.__encrypt_obj = PKCS1_OAEP.new(RSA.importKey(f.read(), passphrase=passphrase))

            else:
                private_key = RSA.generate(2048)
                public_key = private_key.publickey()

                self.__encrypt_obj = PKCS1_OAEP.new(public_key)
                self.__decrypt_obj = PKCS1_OAEP.new(private_key)

                with open(priv_key_full_path, 'wb') as f:
                    f.write(private_key.exportKey(passphrase=passphrase))

                with open(pub_key_full_path, 'wb') as f:
                    f.write(public_key.exportKey(passphrase=passphrase))
        except (ValueError, TypeError, IndexError) as e:
            raise ClientError(str(e))
Пример #14
0
	def createAuthFile(self):
		if os.path.isfile(self.authFileName):
			debug('Auth file already exists')
			raise ret255
		with open (self.authFileName,'w') as authFile:
			# bank public key
			self.secretKey = RSA.generate(2048)
			publicKey = self.secretKey.publickey()
			authFile.write(publicKey.exportKey('PEM'))

			# keys separator
			authFile.write('@@@@@')

			# privateKey for ATM
			atmPrivateKey = RSA.generate(2048)
			authFile.write(atmPrivateKey.exportKey('PEM'))
			self.atmPublicKey = atmPrivateKey.publickey()

			# keys separator
			authFile.write('@@@@@')

			# AES encryption key
			alphabet = string.printable.replace('@','')
			self.AESKey = ''.join([rand.choice(alphabet) for byte in range(32)])
			authFile.write(self.AESKey)

		print 'created'
		sys.stdout.flush()
Пример #15
0
 def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
     if not d:
         self.rsa = RSA.construct((compatLong(n), compatLong(e)))
     else:
         self.rsa = RSA.construct((compatLong(n), compatLong(e),
                                   compatLong(d), compatLong(p),
                                   compatLong(q)))
Пример #16
0
def ensure_user_exists( client, user_email, private_key, **user_kw ):
    """
    Given a user email, ensure that the corresponding
    Syndicate user exists with the given fields.

    This method is idempotent.

    This method can only be called by an admin user.

    @private_key must be a PEM-encoded 4096-bit RSA private key
    
    Return the (created, updated, user), where created==True if the user 
    was created and created==False if the user was read.
    Raise an exception on error.
    """
    
    created = False
    updated = False 

    private_key = private_key.strip()
    try:
        private_key = CryptoKey.importKey( private_key ).exportKey()
        public_key = CryptoKey.importKey( private_key ).publickey().exportKey()
    except:
        log.error("Could not import private key")
        raise Exception("Could not import private key")

    try:
        user = rpc.ms_rpc( client, "read_user", user_email )
    except Exception, e:
        # transport error
        log.exception(e)
        raise Exception("Failed to read '%s'" % user_email )
 def get_private_key(self):
     if self._environment == "PRODUCTION":
         return RSA.importKey(open(testconstants.TestConstants.PRODUCTION_PRIVATE_KEY_PATH, 'r').read(),
                       testconstants.TestConstants.PRODUCTION_PRIVATE_KEY_PASSWORD)
     else:
         return RSA.importKey(open(testconstants.TestConstants.SANDBOX_PRIVATE_KEY_PATH, 'r').read(),
                       testconstants.TestConstants.SANDBOX_PRIVATE_KEY_PASSWORD)
Пример #18
0
def read_key(path, passphrase=None):
    with open(path, "r") as kd:
        if passphrase is not None:
            key = RSA.importKey(kd, passphrase=passphrase)
        else:
            key = RSA.importKey(kd)
    return key
Пример #19
0
    def __init__(self, username, ms_url, user_pkey_pem, syndicate_public_key_pem, debug=False):

        self.config = {}
        self.method_singletons = {}

        try:
            self.config["syndicate_public_key"] = CryptoKey.importKey(syndicate_public_key)
        except:
            raise Exception("Invalid Syndicate public key")

        # sanity check...
        try:
            self.config["user_pkey"] = CryptoKey.importKey(user_pkey_pem)
            assert self.config["user_pkey"].has_private(), "Not a private key"
        except:
            raise Exception("Invalid user private key")

        try:
            host, port, no_tls = parse_url(ms_url)
        except:
            raise Exception("Invalid URL '%s'" % ms_url)

        # populate our config
        self.config["syndicate_host"] = host
        self.config["syndicate_port"] = port
        self.config["no_tls"] = no_tls
        self.config["username"] = username
        self.config["debug"] = debug
        self.config["password"] = password

        Log.set_log_level("DEBUG" if debug else "INFO")
Пример #20
0
def encrypt(v, encrypt_rsapubkey=None, sign_rsaprivkey=None):
	from Crypto.PublicKey import RSA
	from Crypto.Cipher import PKCS1_OAEP
	from Crypto.Cipher import AES
	from Crypto.Signature import PKCS1_PSS
	from Crypto.Hash import SHA512
	out = {}
	if encrypt_rsapubkey:
		encrypt_rsapubkey = RSA.importKey(encrypt_rsapubkey)
		rsa = PKCS1_OAEP.new(encrypt_rsapubkey)
		aeskey = randomString(32)
		iv = randomString(16)
		aes = AES.new(aeskey, AES.MODE_CBC, iv)
		data = varEncode(v).tostring()
		data += "\x00" * (-len(data) % 16)
		out["aesInfo"] = rsa.encrypt(aeskey + iv)
		out["data"] = aes.encrypt(data)
		out["encrypted"] = True
	else:
		out["data"] = varEncode(v).tostring()
		out["encrypted"] = False
	if sign_rsaprivkey:
		sign_rsaprivkey = RSA.importKey(sign_rsaprivkey)
		pss = PKCS1_PSS.new(sign_rsaprivkey)
		h = SHA512.new()
		h.update(out["data"])
		sign = pss.sign(h)
		out["signature"] = sign
	else:
		out["signature"] = None
	return out
Пример #21
0
    def handle_create(self):
        """Create a Rackspace Cloud Servers container.

        Rackspace Cloud Servers does not have the metadata service
        running, so we have to transfer the user-data file to the
        server and then trigger cloud-init.
        """
        # Generate SSH public/private keypair
        if self._private_key is not None:
            rsa = RSA.importKey(self._private_key)
        else:
            rsa = RSA.generate(1024)
        self.private_key = rsa.exportKey()
        public_keys = [rsa.publickey().exportKey("OpenSSH")]
        if self.properties.get("key_name"):
            key_name = self.properties["key_name"]
            public_keys.append(nova_utils.get_keypair(self.nova(), key_name).public_key)
        personality_files = {"/root/.ssh/authorized_keys": "\n".join(public_keys)}

        # Create server
        client = self.nova().servers
        logger.debug("Calling nova().servers.create()")
        server = client.create(self.physical_resource_name(), self.image, self.flavor, files=personality_files)

        # Save resource ID to db
        self.resource_id_set(server.id)

        return server, scheduler.TaskRunner(self._attach_volumes_task())
Пример #22
0
    def __init__(self, data_dir=None, addr=_DEFAULT_ADDR):
        if not data_dir:
            data_dir = ".bitnet"
        data_path = "%s/%s" % (os.path.expanduser("~"), data_dir)

        try:
            os.makedirs(data_path)
        except OSError:
            pass

        id_key_path =  "%s/id.pem" % data_path
        msg_key_path =  "%s/msg.pem" % data_path
        self._client_data_path =  "%s/client_data.json" % data_path

        # ID key
        try:
            id_key_data = open(id_key_path, "r").read()
            self.id_key = ecdsa.SigningKey.from_pem(id_key_data)
        except IOError:
            bits = cryptorandom.getrandbits(256)
            k = binascii.unhexlify(hex(bits)[2:].rstrip("L"))
            secret = ecdsa.util.string_to_number(k)
            self.id_key = ecdsa.SigningKey.from_secret_exponent(
                secret, curve=ecdsa.curves.SECP256k1)
            open(id_key_path, "w").write(self.id_key.to_pem())

        # Messaging key
        try:
            msg_key_data = open(msg_key_path, "r").read()
            self.msg_key = RSA.importKey(msg_key_data)
        except IOError:
            # TODO(ortutay): use 4096 bits instead?
            self.msg_key = RSA.generate(2048, Random.new().read)
            msg_enc = self.msg_key.exportKey('PEM')
            open(msg_key_path, "w").write(msg_enc)


        self._listeners = {}
        self._next_listener_id = 1
        self._seen_messages = set([])
        try:
            self._data = json.loads(open(self._client_data_path, "r").read())
        except:
            self._data = {}
        self.url = "http://%s/bitnetRPC" % addr
        ClaimTokens(self.url, "", self.PubKeyStr(), "", "claimfree")

        # Store messaging key on server, if not already there.
        # TODO(ortutay): If expiration behavior is implemented in the future,
        # this code will need to be updated.
        msgs = self.Get({
            "from-pubkey": self.PubKeyStr(),
            "type": "bitnet.RSAPubKey",
        })
        if not msgs:
            self.Send(None, {
                "from-pubkey": self.PubKeyStr(),
                "type": "bitnet.RSAPubKey",
                "body": self.MsgPubKeyStr(),
            })
Пример #23
0
    def test_sshkeys(self):
        assert isinstance(self.git.getsshkeys(), list)
        self.assertEquals(len(self.git.getsshkeys()), 0)
        # not working due a bug? in pycrypto: https://github.com/dlitz/pycrypto/issues/99

        if ssh_test:
            name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
            rsa_key = RSA.generate(1024)
            self.assertTrue(self.git.addsshkey(title=name, key=str(rsa_key.publickey().exportKey(format="OpenSSH"))))
            self.assertGreater(self.git.getsshkeys(), 0)
            keys = self.git.getsshkeys()
            assert isinstance(keys, list)
            key = self.git.getsshkeys()[0]
            assert isinstance(key, dict)
            self.assertTrue(self.git.deletesshkey(key["id"]))

            name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
            rsa_key = RSA.generate(1024)
            self.assertTrue(self.git.addsshkeyuser(self.user_id, title=name,
                                                   key=str(rsa_key.publickey().exportKey(format="OpenSSH"))))
            self.assertGreater(self.git.getsshkeys(), 0)
            keys = self.git.getsshkeys()
            assert isinstance(keys, list)
            key = self.git.getsshkeys()[0]
            assert isinstance(key, dict)
            self.assertTrue(self.git.deletesshkey(key["id"]))
Пример #24
0
def main(argv):
    encrypt = argv[0]
    keyfile = argv[1]
    service = argv[2]
    username = argv[3]

    if isinstance(encrypt, str):
        if encrypt.lower().startswith('t'):
            encrypt = True
        else:
            encrypt = False

    if encrypt:
        password = argv[4]
        key = RSA.generate(1024)
        cipher = PKCS1_v1_5.new(key)

        keyring.set_password(service, username, key.exportKey())

        with open(keyfile, 'wb') as outf:
            outf.write(cipher.encrypt(password))
    else:
        key = RSA.importKey(keyring.get_password(service, username))
        cipher = PKCS1_v1_5.new(key)

        with open(keyfile, 'rb') as inf:
            return cipher.decrypt(inf.read(), None)
Пример #25
0
 def __init__(self, source_dir, key_file, output_file):
     """
     source_dir  : the path to package resource directory.
     key_file    : the path to RSA private key file, if the file is invalid,
                   generator will create it automatically.
     output_file : the output XPK file path.
     """
     self.source_dir_ = source_dir
     self.output_file_ = output_file
     if not os.path.exists(key_file):
         try:
             print('Start to generate RSA key')
             rng = Random.new().read
             self.RSAkey = RSA.generate(1024, rng)
             kfile = open(key_file, 'w')
             kfile.write(self.RSAkey.exportKey('PEM'))
             kfile.close()
             print('Finished generating RSA key, saved as %s' % key_file)
         except IOError:
             if os.path.exists(key_file):
                 os.remove(key_file)
             traceback.print_exc()
     else:
         self.RSAkey = RSA.importKey(open(key_file, 'r').read())
     self.pubkey = self.RSAkey.publickey().exportKey('DER')
def sign_file(f):
    # TODO: For Part 2, you'll use public key crypto here
    # The existing scheme just ensures the updates start with the line 'Caesar'
    # This is naive -- replace it with something better!
    
    # Generate key pairs
    key = RSA.generate(2048)
    
    # Export public key to file
    export_pukey = key.publickey().exportKey('PEM')
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "wb")
    publickey_file.write(export_pukey)
    publickey_file.close()
    
    # Create RSA object from public key
    publickey_file = open(os.path.join("pastebot.net", "publickey"), "rb").read()
    public_key = RSA.importKey(publickey_file)
    
    # Hash message
    hashed_m = SHA256.new(f)
    
    # Encrypt message using public key
    cipher = PKCS1_cipher.new(public_key)
    ciphertext = cipher.encrypt(f+hashed_m.digest())
    
    # Export private key to be prefixed to ciphertext
    export_prkey = key.exportKey('PEM')
    
    # Sign message using private key
    prkey = RSA.importKey(export_prkey)
    signer = PKCS1_v1_5.new(prkey)
    signature = signer.sign(hashed_m)
    
    # Return private key and ciphertext, as well as signature separately
    return export_prkey + b"\n" + ciphertext, signature
Пример #27
0
    def __init__(self, private_key, certificate):
        """
        Initializes Suds MessagePlugin.

        @type  private_key: string
        @param private_key: RSA - private key filename.
        @type  certificate: string
        @param certificate: X509 certificate filename.
        """
        self.log = logging.getLogger('bankws')
        if os.path.isfile(private_key):
            with open(private_key, 'rb') as f:
                content = f.read()
            try:
                RSAKey.importKey(content)
            except ValueError:
                raise ValueError('Unsupported RSA key format')
            self.keyfile = private_key
        else:
            raise IOError("{0} doesn't exists".format(private_key))

        if os.path.isfile(certificate):
            self.certificate = certificate
        else:
            raise IOError("{0} doesn't exists".format(certificate))
        self.keytype = RSA
Пример #28
0
def aes_query_keys(request):
    data = request.POST
    try:
        fo_id = data['fo']
        try:
            aes_user = AESUser.objects.get(box_id=fo_id)
        except Exception as e:
            private = RSA.generate(1024)
            public = private.publickey()
            aes_user = AESUser(box_id=fo_id, public_rsa=public.exportKey(), secret_rsa=private.exportKey())
            aes_user.save()

        receip_ids = data['recipient'].split(" ")
        i=0
        ret_data = {'n_shared': len(receip_ids)}
        for id in receip_ids:
            try:
                aes_user = AESUser.objects.get(box_id=id)
            except Exception as e:
                private = RSA.generate(1024)
                public = private.publickey()
                aes_user = AESUser(box_id=id, public_rsa=public.exportKey(), secret_rsa=private.exportKey())
                aes_user.save()

            ret_data[str(i)+"_rsa"] = aes_user.public_rsa
            i+=1
    except Exception as e:
        print "Errors " + str(e)
        ret_data={
            'success': False,
            'error': str(e)
        }
    rdata = json.dumps(ret_data)
    return HttpResponse(rdata, content_type='application/json')
Пример #29
0
    def add_pubkey(self):
        """Add a public key to the server."""
        rsakey = RSA.importKey(self.privkey, self.password)
        shibboleth = 'Rosie sent me'
        signature = rsakey.sign(shibboleth, rng(384))[0]
        data = {'username': self.username, 
                'shibboleth': shibboleth, 
                'signature': str(signature),
                'pubkey': self.pubkey}

        url = 'http://' + self.host + '/pubkey/add'
        
        r = requests.post(url, data=data)
        
        if r.status_code != 200:
            r.raise_for_status()

        if not r.cookies['signature']:
            raise SecurityException('Server did not return cookie')
        
        servkey = self.get_pubkey('server')
        rsakey = RSA.importKey(servkey)
        servsig = int(r.cookies['signature'])

        if not rsakey.verify(self.username, (servsig,)):
            raise SecurityException('Could not verify server signature')

        return r.cookies
Пример #30
0
def sign(modulus, exponent, private_exp, message):
    if RSA:
        rsa = RSA((modulus, exponent, private_exp))
        result = rsa._sign(message)
        return result[0]
    else:
        return ''