예제 #1
0
파일: test_rand.py 프로젝트: pyca/pyopenssl
 def test_insufficient_memory(self):
     """
     `OpenSSL.rand.bytes` raises `MemoryError` if more bytes are requested
     than will fit in memory.
     """
     with pytest.raises(MemoryError):
         rand.bytes(sys.maxsize)
예제 #2
0
 def test_bytes_wrong_args(self, args):
     """
     `OpenSSL.rand.bytes` raises `TypeError` if called with a non-`int`
     argument.
     """
     with pytest.raises(TypeError):
         rand.bytes(*args)
예제 #3
0
 def test_insufficient_memory(self):
     """
     `OpenSSL.rand.bytes` raises `MemoryError` if more bytes are requested
     than will fit in memory.
     """
     with pytest.raises(MemoryError):
         rand.bytes(sys.maxsize)
예제 #4
0
파일: test_rand.py 프로젝트: pyca/pyopenssl
 def test_bytes_wrong_args(self, args):
     """
     `OpenSSL.rand.bytes` raises `TypeError` if called with a non-`int`
     argument.
     """
     with pytest.raises(TypeError):
         rand.bytes(*args)
예제 #5
0
 def test_bytes(self):
     """
     Verify that we can obtain bytes from rand_bytes() and
     that they are different each time.  Test the parameter
     of rand_bytes() for bad values.
     """
     b1 = rand.bytes(50)
     self.assertEqual(len(b1), 50)
     b2 = rand.bytes(num_bytes=50)  # parameter by name
     self.assertNotEqual(b1, b2)  #  Hip, Hip, Horay! FIPS complaince
     b3 = rand.bytes(num_bytes=0)
     self.assertEqual(len(b3), 0)
     exc = self.assertRaises(ValueError, rand.bytes, -1)
     self.assertEqual(str(exc), "num_bytes must not be negative")
예제 #6
0
 def test_bytes(self):
     """
     Verify that we can obtain bytes from rand_bytes() and
     that they are different each time.  Test the parameter
     of rand_bytes() for bad values.
     """
     b1 = rand.bytes(50)
     self.assertEqual(len(b1), 50)
     b2 = rand.bytes(num_bytes=50)  # parameter by name
     self.assertNotEqual(b1, b2)  #  Hip, Hip, Horay! FIPS complaince
     b3 = rand.bytes(num_bytes=0) 
     self.assertEqual(len(b3), 0)
     exc = self.assertRaises(ValueError, rand.bytes, -1)
     self.assertEqual(str(exc), "num_bytes must not be negative")
예제 #7
0
파일: test_rand.py 프로젝트: pyca/pyopenssl
 def test_bytes(self):
     """
     Verify that we can obtain bytes from rand_bytes() and that they are
     different each time.  Test the parameter of rand_bytes() for
     bad values.
     """
     b1 = rand.bytes(50)
     assert len(b1) == 50
     b2 = rand.bytes(num_bytes=50)  # parameter by name
     assert b1 != b2  # Hip, Hip, Horay! FIPS complaince
     b3 = rand.bytes(num_bytes=0)
     assert len(b3) == 0
     with pytest.raises(ValueError) as exc:
         rand.bytes(-1)
     assert str(exc.value) == "num_bytes must not be negative"
예제 #8
0
 def test_bytes(self):
     """
     Verify that we can obtain bytes from rand_bytes() and that they are
     different each time.  Test the parameter of rand_bytes() for
     bad values.
     """
     b1 = rand.bytes(50)
     assert len(b1) == 50
     b2 = rand.bytes(num_bytes=50)  # parameter by name
     assert b1 != b2  # Hip, Hip, Horay! FIPS complaince
     b3 = rand.bytes(num_bytes=0)
     assert len(b3) == 0
     with pytest.raises(ValueError) as exc:
         rand.bytes(-1)
     assert str(exc.value) == "num_bytes must not be negative"
예제 #9
0
def privatekey():
    # See https://en.bitcoin.it/wiki/Private_key
    int_pk = 0
    while not (int_pk > 0 and int_pk <= MAX_KEY):  # :)
        pk = hashlib.sha256(rand.bytes(32))
        int_pk = int(pk.hexdigest(), 16)
    return int_pk, wif(pk.digest())
예제 #10
0
def privatekey():
    # See https://en.bitcoin.it/wiki/Private_key
    int_pk = 0
    while not (int_pk > 0 and int_pk <= MAX_KEY):  # :)
        pk = hashlib.sha256(rand.bytes(32))
        int_pk = int(pk.hexdigest(), 16)
    return int_pk, wif(pk.digest())
예제 #11
0
 def generateKey(self,keyFilepath):
     b1 = rand.bytes(16)
     self.hexKey = binascii.hexlify(b1)
     try:
         keyFile = open(keyFilepath,"wb");
     except:
         print "can't open "+keyFilepath;
         raise
     keyFile.write(b1)
     keyFile.close();
예제 #12
0
def create_self_signed_cert(cert_file_path):
    private_key_path = re.sub(r".(pem|crt)$",
                              ".key",
                              cert_file_path,
                              flags=re.IGNORECASE)

    # create public/private key
    key = PKey()
    key.generate_key(TYPE_RSA, 2048)

    # Self-signed cert
    cert = X509()

    #subject = X509Name(cert.get_subject())
    subject = cert.get_subject()
    subject.CN = 'localhost'
    subject.O = 'XYZ Widgets Inc'
    subject.OU = 'IT Department'
    subject.L = 'Seattle'
    subject.ST = 'Washington'
    subject.C = 'US'
    subject.emailAddress = '*****@*****.**'

    cert.set_version(2)
    cert.set_issuer(subject)
    cert.set_subject(subject)
    #cert.set_serial_number(int(os.urandom(16).encode('hex'),16))
    cert.set_serial_number(int(rand.bytes(16).encode('hex'), 16))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(31536000)
    cert.set_pubkey(key)
    cert.add_extensions([
        X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0"),
        X509Extension("keyUsage", True, "keyCertSign, cRLSign"),
        X509Extension("subjectKeyIdentifier", False, "hash", subject=cert),
    ])
    cert.sign(key, 'sha256')

    with open(cert_file_path, 'wb+') as f:
        f.write(dump_certificate(FILETYPE_PEM, cert))
    with open(private_key_path, 'wb+') as f:
        f.write(dump_privatekey(FILETYPE_PEM, key))
예제 #13
0
	def create (self, name):

		if self.state != "none":
			raise IllegalStateError ()

		# sanity check

		if self.client.exists (self.path):
			raise AlreadyExistsError ()

		# create key

		self.root_key = crypto.PKey ()
		self.root_key.generate_key (crypto.TYPE_RSA, 2048)

		# create certificate

		self.root_cert = crypto.X509 ()

		self.root_cert.set_pubkey (self.root_key)

		self.root_cert.set_version (2)

		self.root_cert.set_serial_number (
			struct.unpack ("Q", rand.bytes (8)) [0])

		self.root_cert.get_subject ().C = self.certificate_data ["country"]
		self.root_cert.get_subject ().L = self.certificate_data ["locality"]
		self.root_cert.get_subject ().O = self.certificate_data ["organization"]
		self.root_cert.get_subject ().CN = name

		self.root_cert.gmtime_adj_notBefore (0)
		self.root_cert.gmtime_adj_notAfter (315360000)

		self.root_cert.set_issuer (
			self.root_cert.get_subject ())

		self.root_cert.add_extensions ([

			crypto.X509Extension (
				str ("basicConstraints"),
				True,
				str ("CA:TRUE, pathlen:0")),

			crypto.X509Extension (
				str ("keyUsage"),
				True,
				str ("keyCertSign, cRLSign")),

			crypto.X509Extension (
				str ("subjectKeyIdentifier"),
				False,
				str ("hash"),
				subject = self.root_cert),

		])

		self.root_cert.add_extensions ([

			crypto.X509Extension (
				str ("authorityKeyIdentifier"),
				False,
				str ("keyid,issuer:always"),
				issuer = self.root_cert)

		])

		# sign certificate

		self.root_cert.sign (
			self.root_key,
			str ("sha256"))

		# dump to pem

		self.root_cert_string = crypto.dump_certificate (
			crypto.FILETYPE_PEM,
			self.root_cert)

		self.root_key_string = crypto.dump_privatekey (
			crypto.FILETYPE_PEM,
			self.root_key)

		# write data in "creating" state

		self.data = {

			"authority_state":
				"creating",

			"subject_country":
				self.root_cert.get_subject ().C,

			"subject_locality":
				self.root_cert.get_subject ().L,

			"subject_organization":
				self.root_cert.get_subject ().O,

			"subject_common_name":
				self.root_cert.get_subject ().CN,

		}

		self.client.set_yaml (
			self.path + "/data",
			self.data,
			self.schemas ["certificate-authority"])

		# write other data

		self.client.set_raw (
			self.path + "/certificate",
			self.root_cert_string)

		self.client.set_raw (
			self.path + "/key",
			self.root_key_string)

		self.client.set_raw (
			self.path + "/serial",
			"0")

		# write data in "active" state

		self.data ["authority_state"] = "active"

		self.client.set_yaml (
			self.path + "/data",
			self.data,
			self.schemas ["certificate-authority"])
예제 #14
0
    else:
        return True
        
def encodeInput(html):
    """Encode evil chars..."""
    result = re.sub('"', "&quot;", html)
    result = re.sub("'", "&#39;", result)
    result = re.sub("&", "&amp;", result)
    result = re.sub("<", "&lt;", result)
    result = re.sub(">", "&gt;", result)
    log("User supplied input was encoded", "SUCCESS", "NULL")
    blockUsers()
    return result

#secret key for flask internal session use
secret_key = rand.bytes(512)
password   = generate_pass()
csrf_token_raw = rand.bytes(128)
csrf_token = base64.b64encode(csrf_token_raw)
mimetypes.add_type('image/svg+xml', '.svg')
bindaddr = '127.0.0.1';

# Load default config and override config from an environment variable
# You can also replace password with static password:  PASSWORD='******'
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'skf.db'),
    DEBUG=True,
    SECRET_KEY=secret_key,
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_HTTPONLY = True
))
예제 #15
0
 def getNonce(self):
     return rand.bytes(self.DEFAULT_NONCE_SIZE)
예제 #16
0
 def getNonce(self):
     return rand.bytes(self.DEFAULT_NONCE_SIZE)
예제 #17
0
 def getNonce(cls):
     return rand.bytes(BootstrapHelper.DEFAULT_NONCE_SIZE)
예제 #18
0
def main():
    res = set()
    while len(res) <= 200:
        _d = base64.urlsafe_b64encode(rand.bytes(20))
        print _d
        res.add(_d)
예제 #19
0
 def getNonce(cls):
     return rand.bytes(BootstrapHelper.DEFAULT_NONCE_SIZE)
예제 #20
0
    def create(self, name):

        if self.state != "none":
            raise IllegalStateError()

        # sanity check

        if self.client.exists(self.path):
            raise AlreadyExistsError()

        # create key

        self.root_key = crypto.PKey()
        self.root_key.generate_key(crypto.TYPE_RSA, 2048)

        # create certificate

        self.root_cert = crypto.X509()

        self.root_cert.set_pubkey(self.root_key)

        self.root_cert.set_version(2)

        self.root_cert.set_serial_number(struct.unpack("Q", rand.bytes(8))[0])

        self.root_cert.get_subject().C = self.certificate_data["country"]
        self.root_cert.get_subject().L = self.certificate_data["locality"]
        self.root_cert.get_subject().O = self.certificate_data["organization"]
        self.root_cert.get_subject().CN = name

        self.root_cert.gmtime_adj_notBefore(0)
        self.root_cert.gmtime_adj_notAfter(315360000)

        self.root_cert.set_issuer(self.root_cert.get_subject())

        self.root_cert.add_extensions([
            crypto.X509Extension(str("basicConstraints"), True,
                                 str("CA:TRUE, pathlen:0")),
            crypto.X509Extension(str("keyUsage"), True,
                                 str("keyCertSign, cRLSign")),
            crypto.X509Extension(str("subjectKeyIdentifier"),
                                 False,
                                 str("hash"),
                                 subject=self.root_cert),
        ])

        self.root_cert.add_extensions([
            crypto.X509Extension(str("authorityKeyIdentifier"),
                                 False,
                                 str("keyid,issuer:always"),
                                 issuer=self.root_cert)
        ])

        # sign certificate

        self.root_cert.sign(self.root_key, str("sha256"))

        # dump to pem

        self.root_cert_string = crypto.dump_certificate(
            crypto.FILETYPE_PEM, self.root_cert)

        self.root_key_string = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                      self.root_key)

        # write data in "creating" state

        self.data = {
            "authority_state": "creating",
            "subject_country": self.root_cert.get_subject().C,
            "subject_locality": self.root_cert.get_subject().L,
            "subject_organization": self.root_cert.get_subject().O,
            "subject_common_name": self.root_cert.get_subject().CN,
        }

        self.client.set_yaml(self.path + "/data", self.data,
                             self.schemas["certificate-authority"])

        # write other data

        self.client.set_raw(self.path + "/certificate", self.root_cert_string)

        self.client.set_raw(self.path + "/key", self.root_key_string)

        self.client.set_raw(self.path + "/serial", "0")

        # write data in "active" state

        self.data["authority_state"] = "active"

        self.client.set_yaml(self.path + "/data", self.data,
                             self.schemas["certificate-authority"])
예제 #21
0
def getrandom(keylen=8):
  return rand.bytes(keylen)
예제 #22
0
def generate_ephemeral_certificate(return_as_strings=False):
    """ Create ephemeral self-signed certificate and return it with key.

    Based on http://www.web2pyslices.com/slice/show/1507/generate-ssl-self-signed-certificate-and-key-enable-https-encryption-in-web2py

    Args:
        return_as_strings - Boolean.  If True, will return strings containing file content. If False, will
                                        return path to each file

    Returns:
        tuple of str - either path_to_certfile, path_to_keyfile or certfile_content, keyfile_content

    """
    from OpenSSL import crypto, rand
    from socket import gethostname
    from tempfile import mkstemp
    from os import write as os_write, unlink

    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 4096)

    # poor effort at providing a random serial number for the cert
    randbytes = rand.bytes(4)
    cert_serial = ord(randbytes[0])
    for c in randbytes[1:]:
        cert_serial = cert_serial * ord(c)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "GB"
    cert.get_subject().ST = "State"
    cert.get_subject().L = "City"
    cert.get_subject().O = "Company"
    cert.get_subject().OU = "Organization"
    cert.get_subject().CN = gethostname()
    cert.set_serial_number(cert_serial)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    # we have to write a file to disk as Python's ssl implementation calls C code that expects an actual file
    cfile, cfile_path = mkstemp()
    kfile, kfile_path = mkstemp()
    os_write(cfile, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os_write(kfile, crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

    if return_as_strings:
        cert_data = ''.join(open(cfile_path, 'r').readlines())
        key_data = ''.join(open(kfile_path, 'r').readlines())
        try:
            unlink(cfile_path)
            unlink(kfile_path)
        except:
            pass
        return cert_data, key_data

    else:
        return cfile_path, kfile_path