Optional: crypto backend object from the "cryptography" python library
439678
def load_signing_key(signing_key, crypto_backend=default_backend()):
    
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(signing_key, EllipticCurvePrivateKey):
        return signing_key
    elif isinstance(signing_key, (str, unicode)):
        invalid_strings = [b'-----BEGIN PUBLIC KEY-----']
        invalid_string_matches = [
            string_value in signing_key
            for string_value in invalid_strings
        ]
        if any(invalid_string_matches):
            raise ValueError(
                'Signing key must be a private key, not a public key.')

        try:
            return load_der_private_key(
                signing_key, password=None, backend=crypto_backend)
        except:
            try:
                return load_pem_private_key(
                    signing_key, password=None, backend=crypto_backend)
            except Exception:
                raise ValueError(
                    'Signing key must be a valid private key PEM or DER.')
    else:
        raise ValueError('Signing key must be in string or unicode format.')
689853
def crypt(self, data, crypt_type):
        """"""

        # Error check the data
        if not data:
            return ''
        if len(data) % self.block_size != 0:
            if crypt_type == des.DECRYPT: # Decryption must work on 8 byte blocks
                raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n" + data + ".")
            if not self.getPadding():
                raise ValueError("Invalid data length, data must be a multiple of " + str(self.block_size) + " bytes\n. Try setting the optional padding character")
            else:
                data += (self.block_size - (len(data) % self.block_size)) * self.getPadding()
            # print "Len of data: %f" % (len(data) / self.block_size)

        if self.getMode() == CBC:
            if self.getIV():
                iv = self.__String_to_BitList(self.getIV())
            else:
                raise ValueError("For CBC mode, you must supply the Initial Value (IV) for ciphering")

        # Split the data into blocks, crypting each one seperately
        i = 0
        result = []
        while i < len(data):
            block = self.__String_to_BitList(data[i:i+8])

            # Xor with IV if using CBC mode
            if self.getMode() == CBC:
                if crypt_type == des.ENCRYPT:
                    block = list(map(lambda x, y: x ^ y, block, iv))

                processed_block = self.__des_crypt(block, crypt_type)

                if crypt_type == des.DECRYPT:
                    processed_block = list(map(lambda x, y: x ^ y, processed_block, iv))
                    iv = block
                else:
                    iv = processed_block
            else:
                processed_block = self.__des_crypt(block, crypt_type)


            # Add the resulting crypted block to our list
            result.append(self.__BitList_to_String(processed_block))
            i += 8

        # Return the full crypted string
        if _pythonMajorVersion < 3:
            return ''.join(result)
        else:
            return bytes.fromhex('').join(result)
1022451
def encrypt(self, keys=None, cek="", iv="", **kwargs):
        

        _alg = self["alg"]

        # Find Usable Keys
        if keys:
            keys = self.pick_keys(keys, use="enc")
        else:
            keys = self.pick_keys(self._get_keys(), use="enc")

        if not keys:
            logger.error(KEY_ERR.format(_alg))
            raise NoSuitableEncryptionKey(_alg)

        # Determine Encryption Class by Algorithm
        if _alg in ["RSA-OAEP", "RSA-OAEP-256", "RSA1_5"]:
            encrypter = JWE_RSA(self.msg, **self._dict)
        elif _alg.startswith("A") and _alg.endswith("KW"):
            encrypter = JWE_SYM(self.msg, **self._dict)
        else:  # _alg.startswith("ECDH-ES"):
            encrypter = JWE_EC(**self._dict)
            cek, encrypted_key, iv, params, eprivk = encrypter.enc_setup(
                self.msg, key=keys[0], **self._dict)
            kwargs["encrypted_key"] = encrypted_key
            kwargs["params"] = params

        if cek:
            kwargs["cek"] = cek

        if iv:
            kwargs["iv"] = iv

        for key in keys:
            if isinstance(key, SYMKey):
                _key = key.key
            elif isinstance(key, ECKey):
                _key = key.public_key()
            else:  # isinstance(key, RSAKey):
                _key = key.public_key()

            if key.kid:
                encrypter["kid"] = key.kid

            try:
                token = encrypter.encrypt(key=_key, **kwargs)
                self["cek"] = encrypter.cek if 'cek' in encrypter else None
            except TypeError as err:
                raise err
            else:
                logger.debug(
                    "Encrypted message using key with kid={}".format(key.kid))
                return token
1057213
def load_signing_key(signing_key, crypto_backend=default_backend()):
    
    if isinstance(signing_key, EllipticCurvePrivateKey):
        return signing_key

    elif isinstance(signing_key, (str, unicode)):
        invalid_strings = [b'-----BEGIN PUBLIC KEY-----']
        invalid_string_matches = [
            string_value in signing_key
            for string_value in invalid_strings
        ]
        if any(invalid_string_matches):
            raise ValueError(
                'Signing key must be a private key, not a public key.')

        if is_hex(signing_key):
            try:
                private_key_pem = ECPrivateKey(signing_key).to_pem()
            except:
                pass
            else:
                try:
                    return load_pem_private_key(
                        private_key_pem, password=None, backend=crypto_backend)
                except:
                    raise InvalidPrivateKeyError()

            try:
                return load_der_private_key(
                    signing_key, password=None, backend=crypto_backend)
            except Exception as e:
                traceback.print_exc()
                raise InvalidPrivateKeyError()
        else:
            try:
                return load_pem_private_key(
                    signing_key, password=None, backend=crypto_backend)
            except:
                raise InvalidPrivateKeyError()
    else:
        raise ValueError('Signing key must be in string or unicode format.')
492082
def init(**config):
    
    global _implementation
    global _validate_implementations

    if config.get('crypto_backend') == 'gpg':
        _implementation = gpg
    else:
        _implementation = x509

    _validate_implementations = []
    for mod in config.get('crypto_validate_backends', []):
        if mod == 'gpg':
            _validate_implementations.append(gpg)
        elif mod == 'x509':
            _validate_implementations.append(x509)
        else:
            raise ValueError("%r is not a valid crypto backend" % mod)

    if not _validate_implementations:
        _validate_implementations.append(_implementation)
330668
def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey:
        
        return serialization.load_der_private_key(data, password, default_backend())
62723
def crypto_config_from_kwargs(fallback, **kwargs):
    
    try:
        crypto_config = kwargs.pop("crypto_config")
    except KeyError:
        try:
            fallback_kwargs = {"table_name": kwargs["TableName"]}
        except KeyError:
            fallback_kwargs = {}
        crypto_config = fallback(**fallback_kwargs)
    return crypto_config, kwargs
64980
def authenticationAndCipheringReject():
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x14)  # 00010100
    packet = a / b
    return packet
570708
def crypto_box_keypair():
    
    pk = ffi.new("unsigned char[]", crypto_box_PUBLICKEYBYTES)
    sk = ffi.new("unsigned char[]", crypto_box_SECRETKEYBYTES)

    rc = lib.crypto_box_keypair(pk, sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return (
        ffi.buffer(pk, crypto_box_PUBLICKEYBYTES)[:],
        ffi.buffer(sk, crypto_box_SECRETKEYBYTES)[:],
    )
224410
def crypto_validator(func):
    
    def func_in(*args, **kwargs):
        if not conf.crypto_valid:
            raise ImportError("Cannot execute crypto-related method! "
                              "Please install python-cryptography v1.7 or later.")  # noqa: E501
        return func(*args, **kwargs)
    return func_in
1121745
async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
        
        if self.private_key is None:
            raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key')

        plaintext = await self._loop.run_in_executor(None, lambda: (self.private_key.decrypt(key, padding.PKCS1v15())))

        return plaintext
255333
def crypto_revision_from_options(params)
            case params[:cipher].upcase
            when 'RC4'
                crypto_revision_from_rc4_key(params[:key_size])
            when 'AES'
                crypto_revision_from_aes_key(params[:key_size], params[:hardened])
            else
                raise EncryptionNotSupportedError, "Cipher not supported : #{params[:cipher]}"
            end
        end
787209
function simplecryptor (password, options = {}) {
  const db = this

  // set default ignore
  options.ignore = ['_id', '_rev', '_deleted'].concat(options.ignore)

  const simpleCryptoJS = new SimpleCryptoJS(password)

  // https://github.com/pouchdb-community/transform-pouch#example-encryption
  db.transform({
    incoming: function (doc) {
      return cryptor(simpleCryptoJS, doc, options.ignore, true)
    },
    outgoing: function (doc) {
      return cryptor(simpleCryptoJS, doc, options.ignore, false)
    },
  })
}
804255
function (wallet) {
    var data = JSON.stringify(wallet, null, 2)
    var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0)
    var check = sha256(enc).toString('hex')

    // Throws if there is an encryption error
    Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () {
      throw 'Failed to confirm successful encryption when generating new wallet'
    })

    var postData = {
      guid: wallet.guid,
      sharedKey: wallet.sharedKey,
      length: enc.length,
      payload: enc,
      checksum: check,
      method: 'insert',
      format: 'plain'
    }

    if (email) postData.email = email

    return Blockchain.API.securePost('wallet', postData).then(function () {
      if (isHdWallet) {
        var account = wallet.hd_wallets[0].accounts[0]
        return { guid: wallet.guid, address: account.xpub, label: account.label }
      } else {
        var firstKey = wallet.keys[0]
        return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD }
      }
    })
  }
787853
def encrypt(key_id, plaintext, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        ciphertext = conn.encrypt(
            key_id,
            plaintext,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['ciphertext'] = ciphertext['CiphertextBlob']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
1074176
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
                                        digest=DEFAULT_DIGEST):
    '''
        
    '''
    private_key = OpenSSL.crypto.PKey()
    private_key.generate_key(TYPE_RSA, size)

    request = OpenSSL.crypto.X509Req()
    subject = request.get_subject()
    setattr(subject, 'CN', common_name)
    request.set_pubkey(private_key)
    request.sign(private_key, digest)

    certificate = OpenSSL.crypto.X509()
    certificate.set_serial_number(0)
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5)
    certificate.set_issuer(request.get_subject())
    certificate.set_subject(request.get_subject())
    certificate.set_pubkey(request.get_pubkey())
    certificate.sign(private_key, digest)

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(private_key_path):
        print 'Write {}'.format(private_key_path)
        with open(private_key_path, 'w+') as private_key_file:
            private_key_file.write(
                OpenSSL.crypto.dump_privatekey(FILETYPE_PEM,
                                               private_key).decode('utf-8')
            )
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(private_key_path)

    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Write {}'.format(certificate_path)
        with open(certificate_path, 'w+') as certificate_file:
            certificate_file.write(
                OpenSSL.crypto.dump_certificate(FILETYPE_PEM,
                                                certificate).decode('utf-8')
            )
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
376274
def decrypt payload, armor=false # a RubyMail::Message object
    return unknown_status(@not_working_reason) unless @not_working_reason.nil?

    gpg_opts = {:protocol => GPGME::PROTOCOL_OpenPGP}
    gpg_opts = HookManager.run("gpg-options",
                               {:operation => "decrypt", :options => gpg_opts}) || gpg_opts
    ctx = GPGME::Ctx.new(gpg_opts)
    cipher_data = GPGME::Data.from_str(format_payload(payload))
    if GPGME::Data.respond_to?('empty')
      plain_data = GPGME::Data.empty
    else
      plain_data = GPGME::Data.empty!
    end
    begin
      ctx.decrypt_verify(cipher_data, plain_data)
    rescue GPGME::Error => exc
      return Chunk::CryptoNotice.new(:invalid, "This message could not be decrypted", gpgme_exc_msg(exc.message))
    end
    begin
      sig = self.verified_ok? ctx.verify_result
    rescue ArgumentError => exc
      sig = unknown_status [gpgme_exc_msg(exc.message)]
    end
    plain_data.seek(0, IO::SEEK_SET)
    output = plain_data.read
    output.transcode(Encoding::ASCII_8BIT, output.encoding)

    ## TODO: test to see if it is still necessary to do a 2nd run if verify
    ## fails.
    #
    ## check for a valid signature in an extra run because gpg aborts if the
    ## signature cannot be verified (but it is still able to decrypt)
    #sigoutput = run_gpg "#{payload_fn.path}"
    #sig = self.old_verified_ok? sigoutput, $?

    if armor
      msg = RMail::Message.new
      # Look for Charset, they are put before the base64 crypted part
      charsets = payload.body.split("\n").grep(/^Charset:/)
      if !charsets.empty? and charsets[0] =~ /^Charset: (.+)$/
        output.transcode($encoding, $1)
      end
      msg.body = output
    else
      # It appears that some clients use Windows new lines - CRLF - but RMail
      # splits the body and header on "\n\n". So to allow the parse below to
      # succeed, we will convert the newlines to what RMail expects
      output = output.gsub(/\r\n/, "\n")
      # This is gross. This decrypted payload could very well be a multipart
      # element itself, as opposed to a simple payload. For example, a
      # multipart/signed element, like those generated by Mutt when encrypting
      # and signing a message (instead of just clearsigning the body).
      # Supposedly, decrypted_payload being a multipart element ought to work
      # out nicely because Message::multipart_encrypted_to_chunks() runs the
      # decrypted message through message_to_chunks() again to get any
      # children. However, it does not work as intended because these inner
      # payloads need not carry a MIME-Version header, yet they are fed to
      # RMail as a top-level message, for which the MIME-Version header is
      # required. This causes for the part not to be detected as multipart,
      # hence being shown as an attachment. If we detect this is happening,
      # we force the decrypted payload to be interpreted as MIME.
      msg = RMail::Parser.read output
      if msg.header.content_type =~ %r{^multipart/} && !msg.multipart?
        output = "MIME-Version: 1.0\n" + output
        output.fix_encoding!
        msg = RMail::Parser.read output
      end
    end
    notice = Chunk::CryptoNotice.new :valid, "This message has been decrypted for display"
    [notice, sig, msg]
  end