示例#1
0
    def build_csr(self):
        if not self.private_key:
            if self.key_type == KeyTypes.RSA:
                self.public_key, self.private_key = asymmetric.generate_pair(
                    "rsa", bit_size=self.key_length)
            elif self.key_type == KeyTypes.ECDSA:
                self.public_key, self.private_key = asymmetric.generate_pair(
                    "ec", curve=self.key_curve)
            else:
                raise ClientBadData
        else:
            raise NotImplementedError
            # public_key = gen_public_from_private(self.private_key, self.key_type)  # todo: write function

        data = {
            'common_name': self.common_name,
        }
        if self.email_addresses:
            data['email_address'] = self.email_addresses

        builder = CSRBuilder(data, self.public_key)

        if self.ip_addresses:
            builder.subject_alt_ips = self.ip_addresses
        if self.dns_names:
            builder.subject_alt_domains = self.dns_names

        builder.hash_algo = "sha256"
        builder.subject_alt_domains = [self.common_name]
        self.csr = pem_armor_csr(builder.build(self.private_key)).decode()
        return
示例#2
0
def self_enroll(skip_notify=False):
    assert os.getuid() == 0 and os.getgid(
    ) == 0, "Can self-enroll only as root"

    from certidude import const, config
    common_name = const.FQDN
    os.umask(0o0177)

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        self_public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(config.SELF_KEY_PATH)
    except FileNotFoundError:  # certificate or private key not found
        click.echo("Generating private key for frontend: %s" %
                   config.SELF_KEY_PATH)
        with open(config.SELF_KEY_PATH, 'wb') as fh:
            if public_key.algorithm == "ec":
                self_public_key, private_key = asymmetric.generate_pair(
                    "ec", curve=public_key.curve)
            elif public_key.algorithm == "rsa":
                self_public_key, private_key = asymmetric.generate_pair(
                    "rsa", bit_size=public_key.bit_size)
            else:
                raise NotImplemented(
                    "CA certificate public key algorithm %s not supported" %
                    public_key.algorithm)
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, self_public_key)
    request = builder.build(private_key)
    pid = os.fork()
    if not pid:
        from certidude import authority, config
        from certidude.common import drop_privileges
        drop_privileges()
        assert os.getuid() != 0 and os.getgid() != 0
        path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")
        click.echo("Writing certificate signing request for frontend: %s" %
                   path)
        with open(path, "wb") as fh:
            fh.write(
                pem_armor_csr(request))  # Write CSR with certidude permissions
        authority.sign(common_name,
                       skip_notify=skip_notify,
                       skip_push=True,
                       overwrite=True,
                       profile=config.PROFILES["srv"])
        click.echo("Frontend certificate signed")
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        os.system("systemctl reload nginx")
示例#3
0
def self_enroll():
    assert os.getuid() == 0 and os.getgid(
    ) == 0, "Can self-enroll only as root"

    from certidude import const
    common_name = const.FQDN
    directory = os.path.join("/var/lib/certidude", const.FQDN)
    self_key_path = os.path.join(directory, "self_key.pem")

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        self_public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(self_key_path)
    except FileNotFoundError:  # certificate or private key not found
        with open(self_key_path, 'wb') as fh:
            if public_key.algorithm == "ec":
                self_public_key, private_key = asymmetric.generate_pair(
                    "ec", curve=public_key.curve)
            elif public_key.algorithm == "rsa":
                self_public_key, private_key = asymmetric.generate_pair(
                    "rsa", bit_size=public_key.bit_size)
            else:
                NotImplemented
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, self_public_key)
    request = builder.build(private_key)
    pid = os.fork()
    if not pid:
        from certidude import authority
        from certidude.common import drop_privileges
        drop_privileges()
        assert os.getuid() != 0 and os.getgid() != 0
        path = os.path.join(directory, "requests", common_name + ".pem")
        click.echo("Writing request to %s" % path)
        with open(path, "wb") as fh:
            fh.write(
                pem_armor_csr(request))  # Write CSR with certidude permissions
        authority.sign(common_name,
                       skip_push=True,
                       overwrite=True,
                       profile=config.PROFILES["srv"])
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        if os.path.exists("/etc/systemd"):
            os.system("systemctl reload nginx")
        else:
            os.system("service nginx reload")
示例#4
0
    def generate_certificate(self, domain, save_model):
        """This function takes a domain name as a parameter and then creates
        a certificate and key with the domain name (replacing dots
        by underscores), finally signing the certificate using specified CA and
        returns the path of key and cert files. If you are yet to generate a CA
        then check the top comments"""

        logger.info("SimpleCA: certificate creation request %s" % (domain,))

        ca_private_key = asymmetric.load_private_key(
            self.ca_key,
            password=settings.CA_KEY_PASSWD)
        ca_certificate = asymmetric.load_certificate(self.ca_crt)

        end_entity_public_key, end_entity_private_key = \
            asymmetric.generate_pair('rsa', bit_size=2048)

        builder = CertificateBuilder(
            {
                'country_name': 'CR',
                'state_or_province_name': 'San Jose',
                'locality_name': 'Costa Rica',
                'organization_name': save_model.name,
                "organizational_unit_name": save_model.institution_unit,
                'common_name': domain,
            },
            end_entity_public_key
        )
        now = timezone.now()
        builder.issuer = ca_certificate
        builder.begin_date = now
        builder.end_date = now+timedelta(settings.CA_CERT_DURATION)
        builder.key_usage = set(['digital_signature'])
        end_entity_certificate = builder.build(ca_private_key)
        # settings.CA_CERT_DURATION

        server_public_key, server_private_key = \
            asymmetric.generate_pair('rsa', bit_size=2048)

        save_model.private_key = asymmetric.dump_private_key(
            end_entity_private_key, None)
        save_model.public_key = asymmetric.dump_public_key(
            end_entity_public_key)
        save_model.public_certificate = pem_armor_certificate(
            end_entity_certificate)

        save_model.server_sign_key = asymmetric.dump_private_key(
            server_private_key, None)
        save_model.server_public_key = asymmetric.dump_public_key(
            server_public_key)

        logger.debug("SimpleCA: New certificate for %s is %r" %
                     (domain, save_model.public_certificate))
        return save_model
示例#5
0
def create_certificate():
    root_ca_public_key, root_ca_private_key = asymmetric.generate_pair(
        'rsa', bit_size=2048)

    with open('root_ca.key', 'wb') as f:
        f.write(asymmetric.dump_private_key(root_ca_private_key, u'p'))

    with open('root_ca_public.key', 'wb') as f:
        f.write(asymmetric.dump_public_key(root_ca_public_key, 'pem'))

    builder = CertificateBuilder(
        {
            u'country_name': u'US',
            u'state_or_province_name': u'Massachusetts',
            u'locality_name': u'Amherst',
            u'organization_name': u'Name Certifying service',
            u'common_name': u'NCS Root CA',
        }, root_ca_public_key)
    builder.self_signed = True
    builder.ca = True
    root_ca_certificate = builder.build(root_ca_private_key)

    with open('root_ca.crt', 'wb') as f:
        f.write(pem_armor_certificate(root_ca_certificate))

    # Generate an end-entity key and certificate, signed by the root
    end_entity_public_key, end_entity_private_key = asymmetric.generate_pair(
        'rsa', bit_size=2048)

    with open('ramteja_tadishetti_private.key', 'wb') as f:
        f.write(asymmetric.dump_private_key(end_entity_private_key, u'p'))

    with open('ramteja_tadishetti_public.key', 'wb') as f:
        f.write(asymmetric.dump_public_key(end_entity_public_key, 'pem'))

    builder = CertificateBuilder(
        {
            u'country_name': u'US',
            u'state_or_province_name': u'Massachusetts',
            u'locality_name': u'Amherst',
            u'organization_name': u'Ramteja Tadishetti Corp',
            u'common_name': u'ramtejatadishetti',
        }, end_entity_public_key)
    builder.issuer = root_ca_certificate
    #builder.set_extension( u'1.2.840.113549.1.1.1', 'ramteja', allow_deprecated=False)
    end_entity_certificate = builder.build(root_ca_private_key)

    with open('ramteja_tadishetti.crt', 'wb') as f:
        f.write(pem_armor_certificate(end_entity_certificate))
示例#6
0
def fcm_register(sender_id, token, retries=5):
  """
  generates key pair and obtains a fcm token

  sender_id: sender id as an integer
  token: the subscription token in the dict returned by gcm_register

  returns {"keys": keys, "fcm": {...}}
  """
  # I used this analyzer to figure out how to slice the asn1 structs
  # https://lapo.it/asn1js
  # first byte of public key is skipped for some reason
  # maybe it's always zero
  public, private = generate_pair("ec", curve=unicode("secp256r1"))
  from base64 import b64encode
  __log.debug("# public")
  __log.debug(b64encode(public.asn1.dump()))
  __log.debug("# private")
  __log.debug(b64encode(private.asn1.dump()))
  keys = {
      "public": urlsafe_base64(public.asn1.dump()[26:]),
      "private": urlsafe_base64(private.asn1.dump()),
      "secret": urlsafe_base64(os.urandom(16))
  }
  data = urlencode({
      "authorized_entity": sender_id,
      "endpoint": "{}/{}".format(FCM_ENDPOINT, token),
      "encryption_key": keys["public"],
      "encryption_auth": keys["secret"]
  })
  __log.debug(data)
  req = Request(url=FCM_SUBSCRIBE, data=data.encode("utf-8"))
  resp_data = __do_request(req, retries)
  return {"keys": keys, "fcm": json.loads(resp_data.decode("utf-8"))}
def generate_cert_and_key(cn, filename, keysize, keytype='rsa'):
    ca_key_name = '%s.key' % filename
    ca_cert_name = '%s.crt' % filename

    curdir = pathlib.Path(__file__).parent

    # Generate and save the key and certificate for the root CA
    root_ca_public_key, root_ca_private_key = asymmetric.generate_pair(
        keytype, bit_size=keysize)

    with open(curdir.joinpath(ca_key_name), 'wb') as f:
        f.write(asymmetric.dump_private_key(root_ca_private_key, None))

    builder = CertificateBuilder(
        {
            'country_name': 'US',
            'state_or_province_name': 'Massachusetts',
            'locality_name': 'Newbury',
            'organization_name': 'Codex Non Sufficit LC',
            'common_name': cn,
        }, root_ca_public_key)
    builder.self_signed = True
    builder.ca = True
    root_ca_certificate = builder.build(root_ca_private_key)

    with open(curdir.joinpath(ca_cert_name), 'wb') as f:
        f.write(pem_armor_certificate(root_ca_certificate))
示例#8
0
def build_ca():
    if not os.path.exists(settings.CA_PATH):
        os.makedirs(settings.CA_PATH)

    root_ca_public_key, root_ca_private_key = asymmetric.generate_pair(
        'rsa', bit_size=4096)

    with open(settings.CA_KEY, 'wb') as f:
        f.write(
            asymmetric.dump_private_key(root_ca_private_key,
                                        settings.CA_KEY_PASSWD))

    builder = CertificateBuilder(
        {
            'country_name': 'CR',
            'state_or_province_name': 'San Jose',
            'locality_name': 'Costa Rica',
            'organization_name': 'DFVA Independiente',
            'common_name': 'DFVA Root CA 1',
        }, root_ca_public_key)
    now = timezone.now()
    builder.self_signed = True
    builder.ca = True
    builder.end_date = now + timedelta(settings.CA_CERT_DURATION * 10)
    root_ca_certificate = builder.build(root_ca_private_key)

    with open(settings.CA_CERT, 'wb') as f:
        f.write(pem_armor_certificate(root_ca_certificate))

    builder = CertificateListBuilder('http://crl.dfva.info',
                                     root_ca_certificate, 1000)
    crl_list = builder.build(root_ca_private_key)

    with open(settings.CA_CRL, 'wb') as f:
        f.write(crl_list.dump())
示例#9
0
    def generate_certificate(self, domain, save_model):
        logger.info("Dogtag: certificate creation request %s" % (domain,))

        public_key, private_key = asymmetric.generate_pair(
            'rsa', bit_size=2048)
        data = {
            'common_name': domain,
            'organization_name': save_model.name,
            'organizational_unit_name': save_model.institution_unit,
            'email_address': save_model.email
        }
        data.update(settings.DOGTAG_CERTIFICATE_SCHEME)
        builder = CSRBuilder(
            data,
            public_key
        )
        #builder.subject_alt_domains = ['codexns.io', 'codexns.com']
        request = builder.build(private_key)

        inputs = {
            "cert_request_type": "pkcs10",
            "cert_request": pem_armor_csr(request).decode(),
            "requestor_name": settings.DOGTAG_CERT_REQUESTER,
            "requestor_email": settings.DOGTAG_CERT_REQUESTER_EMAIL,
        }

        logger.debug("Dogtag: request certificate %r" % (inputs,))

        conn = self.get_connection()
        cert_client = pki.cert.CertClient(conn)
        certificates = cert_client.enroll_cert("caServerCert", inputs)

        server_public_key, server_private_key = \
            asymmetric.generate_pair('rsa', bit_size=2048)

        save_model.private_key = asymmetric.dump_private_key(private_key, None)
        save_model.public_key = asymmetric.dump_public_key(public_key)
        save_model.public_certificate = certificates[0].cert.encoded.encode()

        save_model.server_sign_key = asymmetric.dump_private_key(
            server_private_key, None)
        save_model.server_public_key = asymmetric.dump_public_key(
            server_public_key)

        logger.debug("Dogtag: New certificate for %s is %r" %
                     (domain, save_model.public_certificate))
        return save_model
示例#10
0
 def __init__(self, host, port):
     self.socket = socket.socket()
     self.host = host
     self.port = port
     self.message_queue = queue.Queue()
     self.running = False
     self.pair = asymmetric.generate_pair("rsa", 2048)
     self.server_public_key = None
     self.firstRun = True
示例#11
0
    def test_dsa_generate(self):
        public, private = asymmetric.generate_pair('dsa', bit_size=1024)

        self.assertEqual('dsa', public.algorithm)
        self.assertEqual(1024, public.bit_size)

        original_data = b'This is data to sign'
        signature = asymmetric.dsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.dsa_verify(public, signature, original_data, 'sha1')
示例#12
0
    def test_rsa_generate(self):
        public, private = asymmetric.generate_pair('rsa', bit_size=2048)

        self.assertEqual('rsa', public.algorithm)
        self.assertEqual(2048, public.bit_size)

        original_data = b'This is data to sign'
        signature = asymmetric.rsa_pkcs1v15_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'sha1')
示例#13
0
    def test_rsa_generate(self):
        public, private = asymmetric.generate_pair('rsa', bit_size=2048)

        self.assertEqual('rsa', public.algorithm)
        self.assertEqual(2048, public.bit_size)

        original_data = b'This is data to sign'
        signature = asymmetric.rsa_pkcs1v15_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.rsa_pkcs1v15_verify(public, signature, original_data, 'sha1')
示例#14
0
    def test_dsa_generate(self):
        public, private = asymmetric.generate_pair('dsa', bit_size=1024)

        self.assertEqual('dsa', public.algorithm)
        self.assertEqual(1024, public.bit_size)

        original_data = b'This is data to sign'
        signature = asymmetric.dsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.dsa_verify(public, signature, original_data, 'sha1')
示例#15
0
    def test_ec_generate(self):
        public, private = asymmetric.generate_pair('ec', curve='secp256r1')

        self.assertEqual('ec', public.algorithm)
        self.assertEqual('secp256r1', public.asn1.curve[1])

        original_data = b'This is data to sign'
        signature = asymmetric.ecdsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.ecdsa_verify(public, signature, original_data, 'sha1')
示例#16
0
    def test_ec_generate(self):
        public, private = asymmetric.generate_pair('ec', curve='secp256r1')

        self.assertEqual('ec', public.algorithm)
        self.assertEqual('secp256r1', public.asn1.curve[1])

        original_data = b'This is data to sign'
        signature = asymmetric.ecdsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.ecdsa_verify(public, signature, original_data, 'sha1')
示例#17
0
    def _generate_key(self, path):
        # type: (str) -> str
        try:
            with open(path, 'wb') as f:
                _, privkey = asymmetric.generate_pair('rsa', bit_size=2048)
                key_pem = asymmetric.dump_private_key(privkey, None, 'pem')
                f.write(key_pem)
        except IOError:
            raise CommandError("{} is not a path to a writable file.".format(path))

        return key_pem
示例#18
0
 def __init__(self):
     self.host = '0.0.0.0'
     self.port = 2705
     self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.server.bind((self.host, self.port))
     self.server.listen(16)
     self.socks = [self.server]
     self.waitingPublicKey = []
     self.users = {}
     self.pair = asymmetric.generate_pair("rsa", 2048)
     self.now = time.time()
     self.message_queue = queue.Queue()
     self.running = False
示例#19
0
    def test_build_basic(self):
        public_key, private_key = asymmetric.generate_pair('ec', curve='secp256r1')

        builder = CSRBuilder(
            {
                'country_name': 'US',
                'state_or_province_name': 'Massachusetts',
                'locality_name': 'Newbury',
                'organization_name': 'Codex Non Sufficit LC',
                'common_name': 'Will Bond',
            },
            public_key
        )
        builder.subject_alt_domains = ['codexns.io', 'codexns.com']
        request = builder.build(private_key)
        der_bytes = request.dump()

        new_request = asn1crypto.csr.CertificationRequest.load(der_bytes)
        cri = new_request['certification_request_info']

        self.assertEqual('sha256_ecdsa', new_request['signature_algorithm']['algorithm'].native)
        self.assertEqual(1, len(cri['attributes']))
        self.assertEqual('extension_request', cri['attributes'][0]['type'].native)

        extensions = cri['attributes'][0]['values'][0]
        self.assertEqual(4, len(extensions))

        self.assertEqual('basic_constraints', extensions[0]['extn_id'].native)
        self.assertEqual(
            OrderedDict([('ca', False), ('path_len_constraint', None)]),
            extensions[0]['extn_value'].native
        )

        self.assertEqual('extended_key_usage', extensions[1]['extn_id'].native)
        self.assertEqual(
            ['server_auth', 'client_auth'],
            extensions[1]['extn_value'].native
        )

        self.assertEqual('key_usage', extensions[2]['extn_id'].native)
        self.assertEqual(
            set(['digital_signature', 'key_encipherment']),
            extensions[2]['extn_value'].native
        )

        self.assertEqual('subject_alt_name', extensions[3]['extn_id'].native)
        self.assertEqual(
            ['codexns.io', 'codexns.com'],
            extensions[3]['extn_value'].native
        )
示例#20
0
文件: _util.py 项目: wbond/badtls.io
def generate_pair(name, quiet=False, key_type='rsa', key_size=2048):

    if not quiet:
        write('Generating {} keys ... '.format(name), end='')

    public_key, private_key = asymmetric.generate_pair(key_type, bit_size=key_size)

    with open(path.join(certs_dir, '{}.key'.format(name)), 'wb') as f:
        f.write(asymmetric.dump_private_key(private_key, None))

    with open(path.join(certs_dir, '{}.pubkey'.format(name)), 'wb') as f:
        f.write(asymmetric.dump_public_key(public_key))

    if not quiet:
        write('done')
示例#21
0
def generate_pair(name, quiet=False, key_type='rsa', key_size=2048):

    if not quiet:
        write('Generating {} keys ... '.format(name), end='')

    public_key, private_key = asymmetric.generate_pair(key_type,
                                                       bit_size=key_size)

    with open(path.join(certs_dir, '{}.key'.format(name)), 'wb') as f:
        f.write(asymmetric.dump_private_key(private_key, None))

    with open(path.join(certs_dir, '{}.pubkey'.format(name)), 'wb') as f:
        f.write(asymmetric.dump_public_key(public_key))

    if not quiet:
        write('done')
示例#22
0
    def retrieve_cert(self, certificate_request):
        log.debug("Getting certificate status for id %s" %
                  certificate_request.id)

        time.sleep(0.1)
        end_entity_public_key, end_entity_private_key = asymmetric.generate_pair(
            'rsa', bit_size=2048)
        builder = CertificateBuilder(
            {
                'common_name': certificate_request.common_name,
            }, end_entity_public_key)

        root_ca_certificate = asymmetric.load_certificate(ROOT_CA)
        root_ca_private_key = asymmetric.load_private_key(ROOT_CA_KEY)

        builder.issuer = root_ca_certificate
        end_entity_certificate = builder.build(root_ca_private_key)
        return (pem_armor_certificate(end_entity_certificate).decode())
示例#23
0
    def test_ec_generate(self):
        public, private = asymmetric.generate_pair('ec', curve='secp256r1')

        self.assertEqual('ec', public.algorithm)
        self.assertEqual('secp256r1', public.asn1.curve[1])

        original_data = b'This is data to sign'
        signature = asymmetric.ecdsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.ecdsa_verify(public, signature, original_data, 'sha1')

        raw_public = asymmetric.dump_public_key(public)
        asymmetric.load_public_key(raw_public)
        raw_private = asymmetric.dump_private_key(private, None)
        asymmetric.load_private_key(raw_private, None)

        self.assertIsInstance(private.fingerprint, byte_cls)
        self.assertIsInstance(public.fingerprint, byte_cls)
        self.assertEqual(private.fingerprint, public.fingerprint)
示例#24
0
    def test_dsa_generate(self):
        public, private = asymmetric.generate_pair('dsa', bit_size=1024)

        self.assertEqual('dsa', public.algorithm)
        self.assertEqual(1024, public.bit_size)

        original_data = b'This is data to sign'
        signature = asymmetric.dsa_sign(private, original_data, 'sha1')
        self.assertIsInstance(signature, byte_cls)
        asymmetric.dsa_verify(public, signature, original_data, 'sha1')

        raw_public = asymmetric.dump_public_key(public)
        asymmetric.load_public_key(raw_public)
        raw_private = asymmetric.dump_private_key(private, None)
        asymmetric.load_private_key(raw_private, None)

        self.assertIsInstance(private.fingerprint, byte_cls)
        self.assertIsInstance(public.fingerprint, byte_cls)
        self.assertEqual(private.fingerprint, public.fingerprint)
示例#25
0
async def create_message(request):
    body = await request.post()
    session = await get_session(request)
    message = bytes(body['message'], 'UTF-8')
    date = datetime.strptime(body['date'], '%Y-%m-%d')
    public_key, private_key = asymmetric.generate_pair('rsa', bit_size=4096)
    ciphertext = asymmetric.rsa_oaep_encrypt(public_key, message)
    private_key = asymmetric.dump_private_key(private_key, None)
    user = await db.get_user(request.app, session['username'])
    message_uuid = uuid.uuid4().hex
    await db.create_message(
        request.app, {
            'uuid': message_uuid,
            'user': user.uuid,
            'private_key': binascii.hexlify(private_key).decode('UTF-8'),
            'ciphertext': binascii.hexlify(ciphertext).decode('UTF-8'),
            'expires': date
        })
    return web.HTTPFound(location=request.app.router['message_detail'].url_for(
        uuid=message_uuid))
示例#26
0
def self_enroll():
    from certidude import const
    common_name = const.FQDN
    directory = os.path.join("/var/lib/certidude", const.FQDN)
    self_key_path = os.path.join(directory, "self_key.pem")

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(self_key_path)
    except FileNotFoundError:  # certificate or private key not found
        with open(self_key_path, 'wb') as fh:
            public_key, private_key = asymmetric.generate_pair('rsa',
                                                               bit_size=2048)
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo(
                "Certificate %s still valid, delete to self-enroll again" %
                path)
            return

    builder = CSRBuilder({"common_name": common_name}, public_key)
    request = builder.build(private_key)
    with open(os.path.join(directory, "requests", common_name + ".pem"),
              "wb") as fh:
        fh.write(pem_armor_csr(request))
    pid = os.fork()
    if not pid:
        from certidude import authority
        from certidude.common import drop_privileges
        drop_privileges()
        authority.sign(common_name, skip_push=True, overwrite=True)
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        if os.path.exists("/etc/systemd"):
            os.system("systemctl reload nginx")
        else:
            os.system("service nginx reload")
示例#27
0
    def issue_cert(self, csr: CsrBuilder) -> (PrivateKey, Cert):
        public_key, private_key = asymmetric.generate_pair('rsa',
                                                           bit_size=4096)
        builder = CertificateBuilder(
            {
                'country_name': 'US',
                'state_or_province_name': 'Massachusetts',
                'locality_name': 'Newbury',
                'organization_name': 'Codex Non Sufficit LC',
                'common_name': 'Will Bond',
            }, public_key)
        builder.self_signed = True
        cert = builder.build(private_key)
        serial = SerialNumber.from_int(cert.serial_number).as_hex()

        keypath = self._cert_dir / (serial + '.key')
        with keypath.open('wb') as f:
            f.write(asymmetric.dump_private_key(private_key, 'password'))

        certpath = self._cert_dir / (serial + '.pem')
        with certpath.open('wb') as f:
            f.write(pem_armor_certificate(cert))
示例#28
0
def create_certificate():
    root_ca_public_key, root_ca_private_key = asymmetric.generate_pair(
        'rsa', bit_size=2048)

    with open('root_ca.key', 'wb') as f:
        f.write(asymmetric.dump_private_key(root_ca_private_key, u'p'))

    with open('root_ca_public.key', 'wb') as f:
        f.write(asymmetric.dump_public_key(root_ca_public_key, 'pem'))

    builder = CertificateBuilder(
        {
            u'country_name': u'US',
            u'state_or_province_name': u'Massachusetts',
            u'locality_name': u'Amherst',
            u'organization_name': u'Name Certifying service',
            u'common_name': u'NCS Root CA',
        }, root_ca_public_key)
    builder.self_signed = True
    builder.ca = True
    root_ca_certificate = builder.build(root_ca_private_key)

    with open('root_ca.crt', 'wb') as f:
        f.write(pem_armor_certificate(root_ca_certificate))
示例#29
0
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function

import os

from oscrypto import asymmetric
from certbuilder import CertificateBuilder


fixtures_dir = os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures')


root_ca_private_key = asymmetric.load_private_key(os.path.join(fixtures_dir, 'test.key'))
root_ca_certificate = asymmetric.load_certificate(os.path.join(fixtures_dir, 'test.crt'))

root_ocsp_public_key, root_ocsp_private_key = asymmetric.generate_pair('rsa', bit_size=2048)

with open(os.path.join(fixtures_dir, 'test-ocsp.key'), 'wb') as f:
    f.write(asymmetric.dump_private_key(root_ocsp_private_key, 'password', target_ms=20))

builder = CertificateBuilder(
    {
        'country_name': 'US',
        'state_or_province_name': 'Massachusetts',
        'locality_name': 'Newbury',
        'organization_name': 'Codex Non Sufficit LC',
        'organization_unit_name': 'Testing',
        'common_name': 'CodexNS OCSP Responder',
    },
    root_ocsp_public_key
)
示例#30
0
 def __init__(self):
     super(OSCrpto, self).__init__()
     self.key = generate_pair('rsa', bit_size=KEY_SIZE)
示例#31
0
def _gen_key(bits=4096):
    return asymmetric.generate_pair("rsa", bits)
 def ec_secp521r1(self):
     return asymmetric.generate_pair('ec', curve='secp521r1')
示例#33
0
def get_fake_public_key_asn1():
    fake_public_key, _ = asymmetric.generate_pair("rsa", 1024)
    return fake_public_key.asn1
示例#34
0
import sys
import json
import requests

# CSR Generator using CSRBuilder Library
#
# CSRBuilder docs-
# https://github.com/wbond/csrbuilder/blob/master/docs/api.md#subject-attribute
# @author Nathan Steele
#
# Variables for implementation
HOME = os.getenv(
    "USERPROFILE"
)  # this is the file location of the saved CSR/key files OS USERPROFILE is example: C:\Users\n.steele
public_key, private_key = asymmetric.generate_pair(
    'rsa', bit_size=2048
)  # RSA Public key, encryption type, bit size is adjustable, CSRs do not go under 2048
now = datetime.datetime.now()  # generates timestamp for the filenames
date = now.date()
# sg = sendgrid.SendGridClient('Username',
#                              'Password')  # Input username and password of SendGrid account to send emails.
# message = sendgrid.Mail()
errorToEmail = 'ErrorEmail'  # email that it sends error reports too.

# User promopt variables, URL AND DIGICERT ORGANIZATION ID.
domainName = input("Enter the Domain: ")
orgID = input("please input the organziation ID: ")
expireDate = input('expiration date: ')
country = input("Country: ")
state = input("State: ")
city = input("City: ")
 def ec_secp521r1(self):
     return asymmetric.generate_pair('ec', curve='secp521r1')
示例#36
0
#!/usr/bin/env python3

from oscrypto import asymmetric

pub, priv = asymmetric.generate_pair('rsa', 2048)

with open('./secrets/packagecontrol.io.key', 'wb') as f:
    f.write(asymmetric.dump_openssl_private_key(priv, None))

with open('./secrets/packagecontrol.io.pub', 'wb') as f:
    f.write(asymmetric.dump_public_key(pub))
示例#37
0
from __future__ import unicode_literals, division, absolute_import, print_function

import os

from oscrypto import asymmetric
from certbuilder import CertificateBuilder

fixtures_dir = os.path.join(os.path.dirname(__file__), '..', 'tests',
                            'fixtures')

root_ca_private_key = asymmetric.load_private_key(
    os.path.join(fixtures_dir, 'test.key'))
root_ca_certificate = asymmetric.load_certificate(
    os.path.join(fixtures_dir, 'test.crt'))

root_ocsp_public_key, root_ocsp_private_key = asymmetric.generate_pair(
    'rsa', bit_size=2048)

with open(os.path.join(fixtures_dir, 'test-ocsp.key'), 'wb') as f:
    f.write(
        asymmetric.dump_private_key(root_ocsp_private_key,
                                    'password',
                                    target_ms=20))

builder = CertificateBuilder(
    {
        'country_name': 'US',
        'state_or_province_name': 'Massachusetts',
        'locality_name': 'Newbury',
        'organization_name': 'Codex Non Sufficit LC',
        'organization_unit_name': 'Testing',
        'common_name': 'CodexNS OCSP Responder',
示例#38
0
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function

import os

from oscrypto import asymmetric
from certbuilder import CertificateBuilder


fixtures_dir = os.path.join(os.path.dirname(__file__), "..", "tests", "fixtures")

root_ca_public_key, root_ca_private_key = asymmetric.generate_pair("rsa", bit_size=2048)

with open(os.path.join(fixtures_dir, "root.key"), "wb") as f:
    f.write(asymmetric.dump_private_key(root_ca_private_key, "password123", target_ms=20))

builder = CertificateBuilder(
    {
        "country_name": "US",
        "state_or_province_name": "Massachusetts",
        "locality_name": "Newbury",
        "organization_name": "Codex Non Sufficit LC",
        "common_name": "CodexNS Root CA 1",
    },
    root_ca_public_key,
)
builder.self_signed = True
builder.end_entity = False
root_ca_certificate = builder.build(root_ca_private_key)

with open(os.path.join(fixtures_dir, "root.crt"), "wb") as f: