openssl x509 -req -in «/tmp/.../csr.pem» -CAkey «ec private key»
17526
function openssl_x509(csr, ca_key, ca_cert, options) {
  while (csr && 'string' !== typeof csr) csr = csr.csr
  while (ca_cert && 'string' !== typeof ca_cert) ca_cert = ca_cert.cert

  if (!options) options = {}
  if (!csr) throw new Error("Parameter 'csr' is required")
  if (!ca_key) throw new Error("Parameter 'ca_key' is required")
  if (!ca_cert) throw new Error("Parameter 'ca_cert' is required")

  if (!options.extensions)
    options.extensions = extensionConfigForOpenSSL(options, 'v3_req')

  return Promise.all([
      tmpfile(csr),
      tmpfile(ca_cert),
      tmpfile(options.extensions),
      tmpfile(ec_pem.encodePrivateKey(ca_key)) ])
    .then(tmpList => {
      const [tmp_csr, tmp_ca_cert, tmp_ext, tmp_ca_key] = tmpList

      let args = ['x509', '-req', '-sha256']
      args.push('-days', options.days || 1, '-set_serial', options.serial || Date.now().toString())
      args.push('-extensions', 'v3_req', '-extfile', tmp_ext.path)
      args.push('-in', tmp_csr.path, '-CA', tmp_ca_cert.path, '-CAkey', tmp_ca_key.path)

      return finallyCleanupTmpList(openssl_stdout(args, 5), tmpList) })}
1027677
function x509CertificateChain() {
	var self = {
		__TYPE__ : CertificateType.CERT_CHAIN_VERSION_2,
		NumCertBlobs : new type.UInt32Le(),
        CertBlobArray : new type.Factory(function(s) {
        	self.CertBlobArray = new type.Component([]);
        	for(var i = 0; i < self.NumCertBlobs.value; i++) {
        		self.CertBlobArray.obj.push(certBlob().read(s));
        	}
        }),
        padding : new type.BinaryString(null, { readLength : new type.CallableValue(function() {
        	return 8 + 4 * self.NumCertBlobs.value;
        }) }),
        /**
         * @return {object} {n : modulus{bignum}, e : publicexponent{integer}
         */
        getPublicKey : function(){
        	var cert = x509.X509Certificate().decode(new type.Stream(self.CertBlobArray.obj[self.CertBlobArray.obj.length - 1].obj.abCert.value), asn1.ber);
        	var publikeyStream = new type.Stream(cert.value.tbsCertificate.value.subjectPublicKeyInfo.value.subjectPublicKey.toBuffer());
        	var asn1PublicKey = x509.RSAPublicKey().decode(publikeyStream, asn1.ber);
        	return rsa.publicKey(asn1PublicKey.value.modulus.value, asn1PublicKey.value.publicExponent.value);
        }
	};
	
	return new type.Component(self);
}
1367722
def _convert_public_key(ecdsa_curve_name, result):
    """"""
    if ecdsa_curve_name == 'nist256p1':
        if (result[64] & 1) != 0:
            result = bytearray([0x03]) + result[1:33]
        else:
            result = bytearray([0x02]) + result[1:33]
    else:
        result = result[1:]
        keyX = bytearray(result[0:32])
        keyY = bytearray(result[32:][::-1])
        if (keyX[31] & 1) != 0:
            keyY[31] |= 0x80
        result = b'\x00' + bytes(keyY)
    return bytes(result)
1192927
private boolean setupPrivateKeyAndChain(String algorithm) {
        X509ExtendedKeyManager km = sslContext.getX509KeyManager();
        String alias;
        if (conn != null) {
            alias = km.chooseServerAlias(algorithm, null, conn);
        } else {
            alias = km.chooseEngineServerAlias(algorithm, null, engine);
        }
        if (alias == null) {
            return false;
        }
        PrivateKey tempPrivateKey = km.getPrivateKey(alias);
        if (tempPrivateKey == null) {
            return false;
        }
        X509Certificate[] tempCerts = km.getCertificateChain(alias);
        if ((tempCerts == null) || (tempCerts.length == 0)) {
            return false;
        }
        String keyAlgorithm = algorithm.split("_")[0];
        PublicKey publicKey = tempCerts[0].getPublicKey();
        if ((tempPrivateKey.getAlgorithm().equals(keyAlgorithm) == false)
                || (publicKey.getAlgorithm().equals(keyAlgorithm) == false)) {
            return false;
        }
        // For ECC certs, check whether we support the EC domain parameters.
        // If the client sent a SupportedEllipticCurves ClientHello extension,
        // check against that too.
        if (keyAlgorithm.equals("EC")) {
            if (publicKey instanceof ECPublicKey == false) {
                return false;
            }
            ECParameterSpec params = ((ECPublicKey)publicKey).getParams();
            int index = SupportedEllipticCurvesExtension.getCurveIndex(params);
            if (SupportedEllipticCurvesExtension.isSupported(index) == false) {
                return false;
            }
            if ((supportedCurves != null) && !supportedCurves.contains(index)) {
                return false;
            }
        }
        this.privateKey = tempPrivateKey;
        this.certs = tempCerts;
        return true;
    }
1182229
private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
        X509Certificate ret = null;
        CryptoException rete = null;

        List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
        if (SECURITY_PROVIDER != null) { //Add if overridden
            providerList.add(SECURITY_PROVIDER);
        }
        try {
            providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
        } catch (Exception e) {
            logger.warn(e);

        }
        for (Provider provider : providerList) {
            try {
                if (null == provider) {
                    continue;
                }
                CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
                if (null != certFactory) {
                    try (ByteArrayInputStream bis = new ByteArrayInputStream(pemCertificate)) {
                        Certificate certificate = certFactory.generateCertificate(bis);

                        if (certificate instanceof X509Certificate) {
                            ret = (X509Certificate) certificate;
                            rete = null;
                            break;
                        }
                    }

                }
            } catch (Exception e) {

                rete = new CryptoException(e.getMessage(), e);

            }

        }

        if (null != rete) {

            throw rete;

        }

        if (ret == null) {

            logger.error("Could not convert pem bytes");

        }

        return ret;

    }
622448
function createKeys()
    {
        $SSLcnf = [];
        $dn = [];

        //get configurations
        include $this->configKeysPath.'openssl.php';

        // Generate a new private (and public) key pair
        $this->privkey = openssl_pkey_new($SSLcnf);

        // Generate a certificate signing request
        $csr = openssl_csr_new($dn, $this->privkey, $SSLcnf);

        // You will usually want to create a self-signed certificate at this
        // point until your CA fulfills your request.
        // This creates a self-signed cert that is valid for 365 days
        $sscert = openssl_csr_sign($csr, null, $this->privkey, 365, $SSLcnf);

        // Now you will want to preserve your private key, CSR and self-signed
        // cert so that they can be installed into your web server, mail server
        // or mail client (depending on the intended use of the certificate).
        // This example shows how to get those things into variables, but you
        // can also store them directly into files.
        // Typically, you will send the CSR on to your CA who will then issue
        // you with the "real" certificate.

        //CERTIFICADO
        openssl_csr_export_to_file($csr, $this->fncert, false);

        //CERTIFICADO AUTO-ASSINADO
        openssl_x509_export_to_file($sscert, $this->fnsscert, false);

        //CHAVE PRIVADA (private.pem)
        openssl_pkey_export_to_file($this->privkey , $this->fnprivate, null, $SSLcnf);

        //CHAVE PÚBLICA (public.key)
        return file_put_contents($this->fnpublic, openssl_pkey_get_details($this->privkey)['key']);
    }
1017028
def key_file=(*args)
      path, passphrase = args.flatten
      ssl_context.key = OpenSSL::PKey::RSA.new(File.open(path), passphrase)
    end
416295
def private_key_from_der_format(der_key)
      raise ArgumentError, "Missing DER private key" if !der_key

      prepare_if_needed

      buf = FFI::MemoryPointer.from_string(der_key)
      ec_key = d2i_ECPrivateKey(nil, pointer_to_pointer(buf), buf.size-1)
      if ec_key.null?
        raise BTCError, "OpenSSL failed to create EC_KEY with DER private key"
      end
      bn = EC_KEY_get0_private_key(ec_key)
      BN_bn2bin(bn, buf)
      buf.read_string(32)
    end
8727
function getAction(key) {
    const keyString = key.toString();

    if (keyString.match(/CERTIFICATE\sREQUEST-{5}$/m)) {
        return 'req';
    }
    else if (keyString.match(/(PUBLIC|PRIVATE)\sKEY-{5}$/m)) {
        return 'rsa';
    }

    return 'x509';
}
495435
function(pk, challenge, signature) {
    var pem = "-----BEGIN RSA PUBLIC KEY-----\n" 
        + pk.replace(/(.{64})/g, "$1\n")
        + "\n-----END RSA PUBLIC KEY-----";

    var rsa = crypto.createVerify("RSA-SHA256");
    rsa.update(new Buffer(challenge, "base64"));
    if(rsa.verify(pem, signature, "base64"))
    {
        return { result : true };
    }
    else {
        return { result : false };
    }
}
1116979
def _m2crypto_sign(message, ssldir=None, certname=None, **config):
    
    if ssldir is None or certname is None:
        error = "You must set the ssldir and certname keyword arguments."
        raise ValueError(error)

    message['crypto'] = 'x509'

    certificate = M2Crypto.X509.load_cert(
        "%s/%s.crt" % (ssldir, certname)).as_pem()
    # Opening this file requires elevated privileges in stg/prod.
    rsa_private = M2Crypto.RSA.load_key(
        "%s/%s.key" % (ssldir, certname))

    digest = M2Crypto.EVP.MessageDigest('sha1')
    digest.update(fedmsg.encoding.dumps(message))

    signature = rsa_private.sign(digest.digest())

    # Return a new dict containing the pairs in the original message as well
    # as the new authn fields.
    return dict(message.items() + [
        ('signature', signature.encode('base64').decode('ascii')),
        ('certificate', certificate.encode('base64').decode('ascii')),
    ])
903795
def get_public_key(key_info, ctx):
        
        x509_certificate = key_info.find(
            'ds:KeyInfo/ds:X509Data/ds:X509Certificate',
            namespaces={'ds': ns.DSigNs}
        )
        if x509_certificate is not None:
            return load_der_x509_certificate(
                base64.b64decode(x509_certificate.text),
                default_backend()
            ).public_key()
        if ctx.public_key is not None:
            return ctx.public_key
        if isinstance(ctx.private_key, (str, bytes)):
            return ctx.private_key
        return ctx.private_key.public_key()
1026018
def decrypt(self, pkey, cert, flags=0):
        
        if not pkey.cansign:
            raise ValueError("Specified keypair has no private part")
        if pkey != cert.pubkey:
            raise ValueError("Certificate doesn't match private key")
        bio = Membio()
        res = libcrypto.CMS_decrypt(self.ptr, pkey.key, cert.cert, None,
                                    bio.bio, flags)
        if res <= 0:
            raise CMSError("decrypting CMS")
        return str(bio)
69231
function pkcs1pad2(s, n) {
        if (n < s.length + 11) { // TODO: fix for utf-8
            console.error("Message too long for RSA");
            return null;
        }
        var ba = new Array();
        var i = s.length - 1;
        while (i >= 0 && n > 0) {
            var c = s.charCodeAt(i--);
            if (c < 128) { // encode using utf-8
                ba[--n] = c;
            }
            else if ((c > 127) && (c < 2048)) {
                ba[--n] = (c & 63) | 128;
                ba[--n] = (c >> 6) | 192;
            }
            else {
                ba[--n] = (c & 63) | 128;
                ba[--n] = ((c >> 6) & 63) | 128;
                ba[--n] = (c >> 12) | 224;
            }
        }
        ba[--n] = 0;
        var rng = new SecureRandom();
        var x = new Array();
        while (n > 2) { // random non-zero pad
            x[0] = 0;
            while (x[0] == 0) rng.nextBytes(x);
            ba[--n] = x[0];
        }
        ba[--n] = 2;
        ba[--n] = 0;
        return new BigInteger(ba);
    }
547815
def save_x509s(self, x509s):
        """"""

        for file_type in TLSFileType:
            if file_type.value in x509s:
                x509 = x509s[file_type.value]
                if file_type is not TLSFileType.CA:
                    # persist this key or cert to disk
                    tlsfile = getattr(self, file_type.value)
                    if tlsfile:
                        tlsfile.save(x509)
522157
function createSigningRequest($url, $keyPath, $csrPath, $confPath)
    {
        $this->cli->runAsUser(sprintf(
            'openssl req -new -key "%s" -out "%s" -subj "/C=/ST=/O=/localityName=/commonName=%s/organizationalUnitName=/emailAddress=%s%s/" -config "%s"',
            $keyPath, $csrPath, $url, $url, '@laravel.valet', $confPath
        ));
    }
472392
def validate_certificate_and_key(certificate, private_key)
      if !certificate.is_a? OpenSSL::X509::Certificate
        fail ArgumentError, 'certificate must be an OpenSSL::X509::Certificate.'
      elsif !private_key.is_a? OpenSSL::PKey::RSA
        fail ArgumentError, 'private_key must be an OpenSSL::PKey::RSA.'
      elsif public_key_size_bits(certificate) < MIN_KEY_SIZE_BITS
        fail ArgumentError, 'certificate must contain a public key of at ' \
          "least #{MIN_KEY_SIZE_BITS} bits."
      end
    end