Sign certificate with acme_tiny for let's encrypt
508349
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE):
    '''
        
    '''
    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    certificate_request_path = '{}/{}.csr'.format(CERTIFICATES_PATH,
                                                  common_name)
    signed_cert = '{certificates_path}/{common_name}-signed.crt'.format(
        certificates_path=CERTIFICATES_PATH,
        common_name=common_name)

    generate_certificate(common_name, size)

    cmd = 'openssl req -new -sha256 -key {private_key_path}'
    cmd += ' -subj "/CN={common_name}" -out {certificate_request_path}'
    cmd = cmd.format(
        private_key_path=private_key_path,
        common_name=common_name,
        certificate_request_path=certificate_request_path
    )
    p = subprocess.Popen(cmd,
                         shell=True,
                         stdout=subprocess.PIPE,
                         close_fds=True)
    p.communicate()

    _internal_sign_certificate(certificate_path, certificate_request_path,
                              signed_cert)

    cron = "/etc/cron.monthly/acme-renew"
    if not os.path.exists(cron):
        with open(cron, "w") as file:
            file.write("#!/bin/bash\ncozy_management renew_certificates\n")
        st = os.stat(cron)
        os.chmod(cron, st.st_mode | S_IXUSR)
489058
def sign_raw_data(raw_data, privatekey_hex):
    
    if not isinstance(raw_data, (str, unicode)):
        raise ValueError("Data is not a string")

    raw_data = str(raw_data)

    si = ECSigner(privatekey_hex)
    si.update(raw_data)
    return si.finalize()
961745
def crypto_sign_open(signed, vk):
    """"""
    if len(vk) != PUBLICKEYBYTES:
        raise ValueError("Bad verifying key length %d" % len(vk))
    rc = djbec.checkvalid(signed[:SIGNATUREBYTES], signed[SIGNATUREBYTES:], vk)
    if not rc:
        raise ValueError("rc != True", rc)
    return signed[SIGNATUREBYTES:]
380351
def sign(self, identity, blob):
        """"""
        if identity.identity_dict['proto'] in {'ssh'}:
            digest = hashlib.sha256(blob).digest()
        else:
            digest = blob
        return self.sk.sign_digest_deterministic(digest=digest,
                                                 hashfunc=hashlib.sha256)
1133578
def setup_signing(self, secret_key, sign_outgoing=True, allow_unsigned_callback=None, initial_timestamp=None, link_id=None):
        ''''''
        self.mav.signing.secret_key = secret_key
        self.mav.signing.sign_outgoing = sign_outgoing
        self.mav.signing.allow_unsigned_callback = allow_unsigned_callback
        if link_id is None:
            # auto-increment the link_id for each link
            global global_link_id
            link_id = global_link_id
            global_link_id = min(global_link_id + 1, 255)
        self.mav.signing.link_id = link_id
        if initial_timestamp is None:
            # timestamp is time since 1/1/2015
            epoch_offset = 1420070400
            now = max(time.time(), epoch_offset)
            initial_timestamp = now - epoch_offset
            initial_timestamp = int(initial_timestamp * 100 * 1000)
        # initial_timestamp is in 10usec units
        self.mav.signing.timestamp = initial_timestamp
1118819
def sign(self, message, encoder=encoding.RawEncoder):
        
        raw_signed = libnacl.crypto_sign(message, self._signing_key)

        signature = encoder.encode(raw_signed[:libnacl.crypto_sign_BYTES])
        message = encoder.encode(raw_signed[libnacl.crypto_sign_BYTES:])
        signed = encoder.encode(raw_signed)

        return SignedMessage._from_parts(signature, message, signed)
138903
def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
    """"""
    subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
                                    blob=(subkey.data() + secret_bytes))
    packets = list(decode.parse_packets(io.BytesIO(primary_bytes)))
    primary, user_id, signature = packets[:3]

    data_to_sign = primary['_to_hash'] + subkey.data_to_hash()

    if subkey.ecdh:
        embedded_sig = None
    else:
        # Primary Key Binding Signature
        hashed_subpackets = [
            protocol.subpacket_time(subkey.created)]  # signature time
        unhashed_subpackets = [
            protocol.subpacket(16, subkey.key_id())]  # issuer key id
        embedded_sig = protocol.make_signature(
            signer_func=signer_func,
            data_to_sign=data_to_sign,
            public_algo=subkey.algo_id,
            sig_type=0x19,
            hashed_subpackets=hashed_subpackets,
            unhashed_subpackets=unhashed_subpackets)

    # Subkey Binding Signature

    # Key flags: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
    # (certify & sign)                   (encrypt)
    flags = (2) if (not subkey.ecdh) else (4 | 8)

    hashed_subpackets = [
        protocol.subpacket_time(subkey.created),  # signature time
        protocol.subpacket_byte(0x1B, flags)]

    unhashed_subpackets = []
    unhashed_subpackets.append(protocol.subpacket(16, primary['key_id']))
    if embedded_sig is not None:
        unhashed_subpackets.append(protocol.subpacket(32, embedded_sig))
    unhashed_subpackets.append(protocol.CUSTOM_SUBPACKET)

    if not decode.has_custom_subpacket(signature):
        signer_func = keyring.create_agent_signer(user_id['value'])

    signature = protocol.make_signature(
        signer_func=signer_func,
        data_to_sign=data_to_sign,
        public_algo=primary['algo'],
        sig_type=0x18,
        hashed_subpackets=hashed_subpackets,
        unhashed_subpackets=unhashed_subpackets)
    sign_packet = protocol.packet(tag=2, blob=signature)
    return primary_bytes + subkey_packet + sign_packet
71167
def cli(env, identifier):
    """"""

    manager = SoftLayer.SSLManager(env.client)
    certificate = manager.get_certificate(identifier)

    write_cert(certificate['commonName'] + '.crt', certificate['certificate'])
    write_cert(certificate['commonName'] + '.key', certificate['privateKey'])

    if 'intermediateCertificate' in certificate:
        write_cert(certificate['commonName'] + '.icc',
                   certificate['intermediateCertificate'])

    if 'certificateSigningRequest' in certificate:
        write_cert(certificate['commonName'] + '.csr',
                   certificate['certificateSigningRequest'])
1120117
function rsaOaepEncrypt(cek, key) {
  if (key instanceof Buffer) {
    key = key.toString();
  } else if (typeof key !== 'string') {
    throw new TypeError('Key must be a buffer or a string');
  }
  if (!key.includes('-----BEGIN') ||
      !(key.includes('KEY-----') || key.includes('CERTIFICATE-----'))) {
    throw new TypeError('Key must be a PEM formatted RSA public key');
  }
  let options = {key: key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING};
  return buf2b64url(crypto.publicEncrypt(options, cek));
}
1103213
def generate
      cert = OpenSSL::X509::Certificate.new
      configure(cert)
      add_extensions(cert)
      cert.sign(key, OpenSSL::Digest::SHA256.new)
    end
683786
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'):
    
    if isinstance(s, six.text_type):
        raise ValueError("Encode `s` to a bytestring yourself to" +
                         " prevent problems with different default encodings")
    curve = Curve.by_name(curve)
    privkey = curve.passphrase_to_privkey(passphrase)
    return privkey.sign(hashlib.sha512(s).digest(), sig_format)
770613
def sign(message: bytes, sign_key: SignKey) -> Signature:
        

        logger = logging.getLogger(__name__)
        logger.debug("Bls::sign: >>> message: %r, sign_key: %r", message, sign_key)

        c_instance = c_void_p()
        do_call('indy_crypto_bls_sign',
                message, len(message),
                sign_key.c_instance,
                byref(c_instance))

        res = Signature(c_instance)

        logger.debug("Bls::sign: <<< res: %r", res)
        return res
363674
def create_embeded_pkcs7_signature(data, cert, key):
      # noqa: E501

    assert isinstance(data, bytes)
    assert isinstance(cert, str)

    try:
        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
        signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    except crypto.Error as e:
        raise exceptions.CorruptCertificate from e

    bio_in = crypto._new_mem_buf(data)
    pkcs7 = crypto._lib.PKCS7_sign(
        signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS
    )
    bio_out = crypto._new_mem_buf()
    crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)
    signed_data = crypto._bio_to_string(bio_out)

    return signed_data
12436
def create_secret(*args, **kwargs):
    """"""

    to_sign = '-!'.join(args) + '$$'.join(kwargs.values())

    key = settings.SECRET_FOR_SIGNS

    hashed = hmac.new(key, to_sign, sha1)
    return re.sub(r'[\W_]+', '', binascii.b2a_base64(hashed.digest()))
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
565847
def sign(self, pkt, key):
        
        if not self.mac:
            return pkt

        mac = self.new_mac(key)

        if pkt.haslayer(ESP):
            mac.update(raw(pkt[ESP]))
            pkt[ESP].data += mac.finalize()[:self.icv_size]

        elif pkt.haslayer(AH):
            clone = zero_mutable_fields(pkt.copy(), sending=True)
            mac.update(raw(clone))
            pkt[AH].icv = mac.finalize()[:self.icv_size]

        return pkt
900164
def key_sign(rsakey, message, digest):
    """"""
    padding = _asymmetric.padding.PKCS1v15()
    signature = rsakey.sign(message, padding, digest)
    return signature