Export the encrypted private key in NEP-2 format.

        Args:
            passphrase (str): The password to encrypt the private key with, as unicode string

        Returns:
            str: The NEP-2 encrypted private key
972244
def ExportNEP2(self, passphrase):
        
        if len(passphrase) < 2:
            raise ValueError("Passphrase must have a minimum of 2 characters")

        # Hash address twice, then only use the first 4 bytes
        address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest()
        address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
        address_hash = address_hash_tmp2[:4]

        # Normalize password and run scrypt over it with the address_hash
        pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
        derived = scrypt.hash(pwd_normalized, address_hash,
                              N=SCRYPT_ITERATIONS,
                              r=SCRYPT_BLOCKSIZE,
                              p=SCRYPT_PARALLEL_FACTOR,
                              buflen=SCRYPT_KEY_LEN_BYTES)

        # Split the scrypt-result into two parts
        derived1 = derived[:32]
        derived2 = derived[32:]

        # Run XOR and encrypt the derived parts with AES
        xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
        cipher = AES.new(derived2, AES.MODE_ECB)
        encrypted = cipher.encrypt(xor_ed)

        # Assemble the final result
        assembled = bytearray()
        assembled.extend(NEP_HEADER)
        assembled.extend(NEP_FLAG)
        assembled.extend(address_hash)
        assembled.extend(encrypted)

        # Finally, encode with Base58Check
        encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
        return encrypted_key_nep2.decode("utf-8")
330668
def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey:
        
        return serialization.load_der_private_key(data, password, default_backend())
602600
def encrypt_password(self, raw_password):
        
        PraetorianError.require_condition(
            self.pwd_ctx is not None,
            "Praetorian must be initialized before this method is available",
        )
        return self.pwd_ctx.encrypt(raw_password, scheme=self.hash_scheme)
391171
def ed25519_private_key_to_string(key):
    
    return base64.b64encode(key.private_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PrivateFormat.Raw,
        encryption_algorithm=serialization.NoEncryption()
    ), None).decode('utf-8')
1084671
def from_private_key(path: str) -> SigningKeyType:
        
        key = load_key(path)
        key.pubkey = Base58Encoder.encode(key.vk)
        return key
42826
async function decryptPBES2(decoded, passphrase){
  const kdf = decoded.encryptionAlgorithm.parameters.keyDerivationFunc;
  const eS = decoded.encryptionAlgorithm.parameters.encryptionScheme;

  // pbkdf2
  const keyLength = params.encryptionSchemes[eS.algorithm].keyLength; // get keyLength
  let key;
  if(kdf.algorithm === 'pbkdf2') {
    const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
    if (kdf.parameters.salt.type !== 'specified') throw new Error('UnsupportedSaltSource');
    const salt = new Uint8Array(kdf.parameters.salt.value);
    const iterationCount = kdf.parameters.iterationCount.toNumber();
    const prf = kdf.parameters.prf.algorithm;
    key = await pbkdf.pbkdf2(pBuffer, salt, iterationCount, keyLength, params.pbkdf2Prfs[prf].hash);
  }
  else throw new Error('UnsupportedKDF');

  // decryption
  // TODO other encryption schemes
  let out;
  if(eS.algorithm === 'des-ede3-cbc'){
    const iv = eS.parameters;
    const CBC = des.CBC.instantiate(des.EDE);
    const pt = CBC.create({ type: 'decrypt', key, iv });
    out = Buffer.from(pt.update(decoded.encryptedData).concat(pt.final()));
  }
  else if (eS.algorithm === 'aes128-cbc' || eS.algorithm === 'aes192-cbc'|| eS.algorithm === 'aes256-cbc'){
    const iv = new Uint8Array(eS.parameters);
    out = Buffer.from( await jscaes.decrypt(
      new Uint8Array(decoded.encryptedData), key, {name: 'AES-CBC', iv}
    ));
  } else throw new Error('UnsupportedEncryptionAlgorithm');

  return OneAsymmetricKey.decode(out, 'der');
}
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
630363
public InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {

    PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream);
    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
    InputStream clear;

    try {
      clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(
          new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
              .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));

      JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);

      return new LazyMaterializeDecryptorInputStream(pgpFact);
    } catch (PGPException e) {
      throw new IOException(e);
    }
  }
770471
def load_private_key(pem_path, passphrase_bytes=None):
    """"""
    with open(pem_path, "rb") as f:
        return cryptography.hazmat.primitives.serialization.load_pem_private_key(
            data=f.read(),
            password=passphrase_bytes,
            backend=cryptography.hazmat.backends.default_backend(),
        )
1332548
public String encrypt( final String str, final String passPhrase )
        throws PlexusCipherException
    {
        if ( str == null || str.length() < 1 )
        {
            return str;
        }

        return _cipher.encrypt64( str, passPhrase );
    }
476373
public static function loadPrivate($pem, $passphrase = '')
    {
        if (!is_string($pem)) {
            throw new \InvalidArgumentException();
        }

        if (!is_string($passphrase)) {
            throw new \InvalidArgumentException();
        }

        /// @FIXME support passphrase-protected EdDSA private keys.
        if ($passphrase !== '') {
            throw new \RuntimeException();
        }

        if (strncmp($pem, 'file://', 7) === 0) {
            $key = file_get_contents(substr($pem, 7));
        } else {
            $key = $pem;
        }

        $header = '-----BEGIN OPENSSH PRIVATE KEY-----';
        $footer = '-----END OPENSSH PRIVATE KEY-----';
        if (strncmp($key, $header, strlen($header)) !== 0) {
            throw new \InvalidArgumentException();
        } elseif (substr($key, -strlen($footer)) !== $footer) {
            throw new \InvalidArgumentException();
        }
        $key = base64_decode(substr($key, strlen($header), -strlen($footer)));

        if (strncmp($key, static::AUTH_MAGIC, strlen(static::AUTH_MAGIC))) {
            throw new \InvalidArgumentException();
        }

        $decoder = new \fpoirotte\Pssht\Wire\Decoder();
        $decoder->getBuffer()->push(substr($key, strlen(static::AUTH_MAGIC)));

        $ciphername = $decoder->decodeString();

        /// @FIXME support encrypted private keys
        if ($ciphername !== 'none') {
            throw new \InvalidArgumentException();
        }

        $kdfname    = $decoder->decodeString();
        $kdfoptions = $decoder->decodeString();
        $numKeys    = $decoder->decodeUint32();
        $publicKey  = array();

        // Block malicious inputs
        if ($numKeys <= 0 || $numKeys >= 0x80000000) {
            throw new \InvalidArgumentException();
        }

        for ($i = 0; $i < $numKeys; $i++) {
            $tmp = new \fpoirotte\Pssht\Wire\Decoder();
            $tmp->getBuffer()->push($decoder->decodeString());

            // Reject unknown key identifiers
            if ($tmp->decodeString() !== static::getName()) {
                continue;
            }

            $publicKey[$i] = $tmp->decodeString();
        }

        $tmp = new \fpoirotte\Pssht\Wire\Decoder();
        $tmp->getBuffer()->push($decoder->decodeString());

        // Both "checkint" fields must have the same value.
        if ($tmp->decodeUint32() !== $tmp->decodeUint32()) {
            throw new \InvalidArgumentException();
        }

        // Reject unknown identifiers.
        if ($tmp->decodeString() !== static::getName()) {
            throw new \InvalidArgumentException();
        }

        // Discard public key blob (duplicate).
        $tmp->decodeString();

        $secretKey = array();
        for ($i = 0; $i < $numKeys; $i++) {
            $secretKey[$i] = $tmp->decodeString();
            // Discard comment field.
            $tmp->decodeString();
        }

        // Should we also ensure that a correct padding
        // has been applied?

        $pk = reset($publicKey);
        if (!isset($secretKey[key($publicKey)])) {
            throw new \InvalidArgumentException();
        }
        $sk = $secretKey[key($publicKey)];

        return new static($pk, $sk);
    }
418778
async function _pbkdf2Passphrase(passphrase, salt) {
  if (window.crypto && window.crypto.subtle) {
    console.log('[crypt] Using native PBKDF2');

    const k = await window.crypto.subtle.importKey(
      'raw',
      Buffer.from(passphrase, 'utf8'),
      { name: 'PBKDF2' },
      false,
      ['deriveBits'],
    );

    const algo = {
      name: 'PBKDF2',
      salt: Buffer.from(salt, 'hex'),
      iterations: DEFAULT_PBKDF2_ITERATIONS,
      hash: 'SHA-256',
    };

    const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8);
    return Buffer.from(derivedKeyRaw).toString('hex');
  } else {
    console.log('[crypt] Using Forge PBKDF2');
    const derivedKeyRaw = forge.pkcs5.pbkdf2(
      passphrase,
      forge.util.hexToBytes(salt),
      DEFAULT_PBKDF2_ITERATIONS,
      DEFAULT_BYTE_LENGTH,
      forge.md.sha256.create(),
    );

    return forge.util.bytesToHex(derivedKeyRaw);
  }
}
113245
def to_signed_str(self, private, public, passphrase=None):
        '''
        
        '''
        from pyxmli import xmldsig
        try:
            from Crypto.PublicKey import RSA
        except ImportError:
            raise ImportError('PyCrypto 2.5 or more recent module is ' \
                              'required to enable XMLi signing.\n' \
                              'Please visit: http://pycrypto.sourceforge.net/')
            
        if not isinstance(private, RSA._RSAobj):
            private = RSA.importKey(private.read(), passphrase=passphrase)
        
        if not isinstance(public, RSA._RSAobj):
            public = RSA.importKey(public.read())
            
        return to_unicode(xmldsig.sign(to_unicode(self.to_string()),
                                       private, public))
936795
public static function rsaPrivateDecrypt(
        $str,
        $privateKeyPath,
        $passPhrase = '',
        $padding = OPENSSL_PKCS1_PADDING,
        $format = self::FORMAT_HEX
    )
    {
        $str = trim($str);

        switch ($format) {
            case self::FORMAT_HEX:
                $str = hex2bin($str);
                break;
            case self::FORMAT_BASE64:
                $str = EncodeHelper::base64Decode($str);
                break;
            default:
                $str = hex2bin($str);
        }

        openssl_private_decrypt(
            $str,
            $decrypted,
            openssl_get_privatekey(file_get_contents($privateKeyPath), $passPhrase),
            $padding
        );

        return trim($decrypted);
    }
1204226
public String decryptDecorated( final String str, final String passPhrase )
        throws PlexusCipherException
    {
        if ( str == null || str.length() < 1 )
        {
            return str;
        }

        if ( isEncryptedString( str ) )
        {
            return decrypt( unDecorate( str ), passPhrase );
        }

        return decrypt( str, passPhrase );
    }
1169155
def to_array(self):
        
        array = super(EncryptedCredentials, self).to_array()
        array['data'] = u(self.data)  # py2: type unicode, py3: type str
        array['hash'] = u(self.hash)  # py2: type unicode, py3: type str
        array['secret'] = u(self.secret)  # py2: type unicode, py3: type str
        return array
203427
public static boolean checkPassPhrase(File keyFilePath, String passPhrase) {
        KeyPair key = parsePrivateKeyFile(keyFilePath);
        boolean isValidPhrase = passPhrase != null && !passPhrase.trim().isEmpty();
        if (key == null) {
            return false;
        } else if (key.isEncrypted() != isValidPhrase) {
            return false;
        } else if (key.isEncrypted()) {
            return key.decrypt(passPhrase);
        }
        return true;
    }