Open a JSON-encoded private key and return it

    If a password file is provided, uses it to decrypt the key. If not, the
    password is asked interactively. Raw hex-encoded private keys are supported,
    but deprecated.
555930
def get_private_key(key_path, password_path=None):
    """"""

    assert key_path, key_path
    if not os.path.exists(key_path):
        log.fatal('%s: no such file', key_path)
        return None

    if not check_permission_safety(key_path):
        log.fatal('Private key file %s must be readable only by its owner.', key_path)
        return None

    if password_path and not check_permission_safety(password_path):
        log.fatal('Password file %s must be readable only by its owner.', password_path)
        return None

    with open(key_path) as keyfile:
        private_key = keyfile.readline().strip()

        if is_hex(private_key) and len(decode_hex(private_key)) == 32:
            log.warning('Private key in raw format. Consider switching to JSON-encoded')
        else:
            keyfile.seek(0)
            try:
                json_data = json.load(keyfile)
                if password_path:
                    with open(password_path) as password_file:
                        password = password_file.readline().strip()
                else:
                    password = getpass.getpass('Enter the private key password: ')
                if json_data['crypto']['kdf'] == 'pbkdf2':
                    password = password.encode()  # type: ignore
                private_key = encode_hex(decode_keyfile_json(json_data, password))
            except ValueError:
                log.fatal('Invalid private key format or password!')
                return None

    return private_key
1042088
def decrypt(data, opts={})
      data = data.to_s
      raise "No private key set!" unless @key.private?
      unless opts[:binary]
        data = Base64.decode64(data)
      end
      @key.private_decrypt(data)
    end
778468
def decrypt(self, recipient_key):
        
        ephem = UserLock.from_b64(self.dict['ephemeral'])
        ephem_box = nacl.public.Box(recipient_key.private_key, ephem.public_key)
        # Scan available entries in decryptInfo and try to decrypt each; break when
        # successful with any.
        for nonce, crypted_decryptInfo in self.dict['decryptInfo'].items():
            raw_nonce = b64decode(nonce)
            crypted_decryptInfo = b64decode(crypted_decryptInfo)
            try:
                decryptInfo_raw = ephem_box.decrypt(crypted_decryptInfo, raw_nonce)
                decryptInfo = json.loads(decryptInfo_raw.decode('utf8'))
                success_nonce = raw_nonce
                break
            except Exception as E:
                #print("Decoding exception: '{}' - with ciphertext '{}'".format(E, crypted_decryptInfo))
                pass
        else:
            raise ValueError("No decryptInfo block found for this recipient Key.")
        if not recipient_key.userID == decryptInfo['recipientID']:
            raise ValueError("Decrypted a meta block but stated recipient is not this private key!")
        # Now work with decryptInfo and success_nonce to extract file data.
        senderKey = UserLock.from_id(decryptInfo['senderID'])
        senderBox = nacl.public.Box(recipient_key.private_key, senderKey.public_key)
        fileInfo_raw = b64decode(decryptInfo['fileInfo'])
        fileInfo_decrypted = senderBox.decrypt(fileInfo_raw, success_nonce).decode('utf8')
        fileInfo = json.loads(fileInfo_decrypted)
        # Overwrite decryptInfo's fileInfo key
        decryptInfo['fileInfo'] = fileInfo
        return decryptInfo
23027
private Object decrypt(JsonObject object, String providerName) throws Exception {
        Object decrypted;

        String key = object.getString("kid");
        String alg = object.getString("alg");

        CryptoProvider provider = this.cryptoManager.getProvider(providerName);

        if (!provider.checkAlgorithmNameMatch(alg)) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        if (!key.contentEquals(provider.getKeyStoreProvider().publicKeyName())) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        byte[] encryptedBytes;
        String encryptedValueWithConfig;

        if (object.containsKey("iv")) {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("iv") + object.getString("ciphertext");

            byte[] encrypted = Base64.decode(object.getString("ciphertext"));
            byte[] iv = Base64.decode(object.getString("iv"));
            encryptedBytes = new byte[iv.length + encrypted.length];
            System.arraycopy(iv, 0, encryptedBytes, 0, iv.length);
            System.arraycopy(encrypted, 0, encryptedBytes, iv.length, encrypted.length);
        } else {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("ciphertext");
            encryptedBytes = Base64.decode(object.getString("ciphertext"));
        }

        if (object.containsKey("sig")) {
            byte[] signature = Base64.decode(object.getString("sig"));

            if (!provider.verifySignature(encryptedValueWithConfig.getBytes(), signature)) {
                cryptoManager.throwSigningFailedEx(providerName);
            }
        }

        byte[] decryptedBytes = provider.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes, Charset.forName("UTF-8"));
        decrypted = JacksonTransformers.MAPPER.readValue(decryptedString, Object.class);
        if (decrypted instanceof Map) {
            decrypted = JsonObject.from((Map<String, ?>) decrypted);
        } else if (decrypted instanceof List) {
            decrypted = JsonArray.from((List<?>) decrypted);
        }
        return decrypted;
    }
334846
def key_pair_from_ed25519_key(hex_private_key):
    """"""
    priv_key = crypto.Ed25519SigningKey(bytes.fromhex(hex_private_key)[:32], encoding='bytes')
    public_key = priv_key.get_verifying_key()
    return CryptoKeypair(private_key=priv_key.encode(encoding='base58').decode('utf-8'),
                         public_key=public_key.encode(encoding='base58').decode('utf-8'))
907622
def get_uncompressed_private_and_public_keys( privkey_str ):
    
    if not isinstance(privkey_str, (str, unicode)):
        raise ValueError("private key given is not a string")

    pk = ecdsa_private_key(str(privkey_str))
    pk_hex = pk.to_hex()

    # force uncompressed
    if len(pk_hex) > 64:
        if pk_hex[-2:] != '01':
            raise ValueError("private key does not end in '01'")

        pk_hex = pk_hex[:64]

    pubk_hex = ecdsa_private_key(pk_hex).public_key().to_hex()
    return pk_hex, pubk_hex
1184364
def read_data(self, password=None):
        
        fp = self.fp
        fp.seek(self.__data_start)

        if self.is_encrypted():
            fp = self._decrypt(fp, password=password)

        if self.compression == CompressionType.ZLIB:
            fp = self._decompress(fp)

        if self.stream:
            mode = 'r|*'
        else:
            mode = 'r:*'
        tar = tarfile.open(fileobj=fp, mode=mode)
        return tar
815575
def decrypt_file(path, key)
			data = read_file(path)
			decryptedFile = File.new(path, "wb")
			decryptedFile.write(decrypt(data, key))
			decryptedFile.close
		end
1204301
function decrypt(input, secret) {
  // Ensure we have something to decrypt
  if (!input) {
    return new Error('You must provide a value to decrypt');
  }
  // Ensure we have the secret used to encrypt this value
  if (!secret) {
    return new Error('A \'secret\' is required to decrypt');
  }

  // turn string into an object
  try {
      input = JSON.parse(input);
  } catch (err) {
      return new Error('Unable to parse string input as JSON');
  }

  // Ensure our input is a valid object with 'iv', 'salt', and 'value'
  if (!input.iv || !input.salt || !input.value) {
    return new Error('Input must be a valid object with \'iv\', \'salt\', and \'value\' properties');
  }

  var salt = new Buffer(input.salt, 'base64'),
    iv = new Buffer(input.iv, 'base64'),
    keyLength = input.keyLength,
   iterations = input.iterations;

  try {

    var key = cryptoLib.pbkdf2Sync(secret, salt, iterations, keyLength / 8, 'sha1'),
      decipher = cryptoLib.createDecipheriv(CIPHER, key, iv);

    var decryptedValue = decipher.update(input.value, 'base64', 'utf8');
    decryptedValue += decipher.final('utf8');

    return decryptedValue;

  } catch (err) {
    return new Error('Unable to decrypt value due to: ' + err);
  }
}
275414
function extractReadableKeys (dir, options) {
  const pwd = options.input
  prompt.start()
  prompt.get(promptSchema, (err, { password }) => {
    const key = fs.readFileSync(path.join(pwd, dir, 'sign_key'))
    const pubKey = fs.readFileSync(path.join(pwd, dir, 'sign_key.pub'))

    const decrypted = Crypto.decryptPrivateKey(password, key)

    const privateHex = Buffer.from(decrypted).toString('hex')
    const decryptedPub = Crypto.decryptPubKey(password, pubKey)

    console.log(`Private key (hex): ${privateHex}`)
    console.log(`Public key (base check): ak_${Crypto.encodeBase58Check(decryptedPub)}`)
    console.log(`Public key (hex): ${decryptedPub.toString('hex')}`)
  })
}
1129466
def _encode_key(self, key):
        
        if isinstance(key, str) or isinstance(key, unicode):
            key = key.encode(self._keyencoding)
        elif not isinstance(key, bytes):
            raise TypeError("key must be bytes or str")
        return codecs.encode(key, 'hex_codec').decode(self._keyencoding)
406715
def decrypt_file(file_path, recipient_key, *, base64=False):
    ""
    crypto.assert_type_and_length('recipient_key', recipient_key, crypto.UserLock)
    with open(file_path, "rb") as I:
        contents = I.read()
        if base64:
            contents = crypto.b64decode(contents)
        crypted = crypto.MiniLockFile(contents)
    return crypted.decrypt(recipient_key)
1265995
def decrypt password = nil, ciphertext = nil
      return @raw_content if @deferred_encryption && @raw_content

      # Given a private key and a nil password OpenSSL::PKey::RSA.new() will
      # *prompt* for a password, we default to an empty string to avoid that.
      ciphertext ||= @instance[@name]
      unless @deferred_encryption
        return nil if ciphertext.nil?
        return "" if ciphertext.empty?
      end

      return "*encrypted*" if password.nil?
      unless @private_key
        raise StrongboxError.new("#{@instance.class} model does not have private key_file")
      end

      if ciphertext
        ciphertext = Base64.decode64(ciphertext) if @base64
        private_key = get_rsa_key(@private_key,password)
        if @symmetric == :always
          random_key = @instance[@symmetric_key]
          random_iv = @instance[@symmetric_iv]
          if @base64
            random_key = Base64.decode64(random_key)
            random_iv = Base64.decode64(random_iv)
          end
          cipher = Cipher.new(@symmetric_cipher)
          cipher.decrypt
          cipher.key = private_key.private_decrypt(random_key,@padding)
          cipher.iv = private_key.private_decrypt(random_iv,@padding)
          plaintext = cipher.update(ciphertext)
          plaintext << cipher.final
        else
          plaintext = private_key.private_decrypt(ciphertext,@padding)
        end
      else
        nil
      end
    end
1195835
def DecryptPrivateKey(self, encrypted_private_key):
        
        aes = AES.new(self._master_key, AES.MODE_CBC, self._iv)
        return aes.decrypt(encrypted_private_key)
1081601
private static String decode_password(String encoded_string, String crypto_algorithm) {
        /*
         * decoding process:
         * 
         * -- check for empty algorithm tag
         * -- convert input String to byte[] using base64 decoding
         * -- decipher byte[]
         * -- convert byte[] to String using UTF8 conversion code
         */

        StringBuilder buffer = new StringBuilder();

        if (crypto_algorithm.length() == 0) {
            // crypto algorithm is empty ... don't decode password
            buffer.append(encoded_string);
        } else {
            // decode password with specified crypto algorithm
            String decoded_string = null;
            if (encoded_string.length() > 0) {
                // convert viewable string to encrypted password byte[]
                byte[] encrypted_bytes = convert_viewable_to_bytes(encoded_string);
                logger.logp(Level.FINEST, PasswordUtil.class.getName(), "decode_password", "byte array before decoding\n" + PasswordHashGenerator.hexDump(encrypted_bytes));

                if (encrypted_bytes == null) {
                    // base64 decoding failed
                    logger.logp(Level.SEVERE, PasswordUtil.class.getName(), "decode_password", "PASSWORDUTIL_INVALID_BASE64_STRING");
                    return null;
                }

                if (encrypted_bytes.length > 0) {
                    // decrypt encrypted password byte[] with specified crypto algorithm

                    byte[] decrypted_bytes = null;

                    try {
                        decrypted_bytes = PasswordCipherUtil.decipher(encrypted_bytes, crypto_algorithm);
                    } catch (InvalidPasswordCipherException e) {
                        logger.logp(Level.SEVERE, PasswordUtil.class.getName(), "decode_password", "PASSWORDUTIL_CYPHER_EXCEPTION", e);
                        return null;
                    } catch (UnsupportedCryptoAlgorithmException e) {
                        logger.logp(Level.SEVERE, PasswordUtil.class.getName(), "decode_password", "PASSWORDUTIL_UNKNOWN_ALGORITHM_EXCEPTION", e);
                        return null;
                    }

                    if ((decrypted_bytes != null) && (decrypted_bytes.length > 0)) {
                        // convert decrypted password byte[] to string
                        decoded_string = convert_to_string(decrypted_bytes);
                    }
                }
            }

            if ((decoded_string != null) && (decoded_string.length() > 0)) {
                // append decoded string
                buffer.append(decoded_string);
            }
        }

        return buffer.toString();
    }
1165067
def _encrypt_private(self, ret, dictkey, target):
        '''
        
        '''
        # encrypt with a specific AES key
        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             target)
        key = salt.crypt.Crypticle.generate_key_string()
        pcrypt = salt.crypt.Crypticle(
            self.opts,
            key)
        try:
            pub = salt.crypt.get_rsa_pub_key(pubfn)
        except (ValueError, IndexError, TypeError):
            return self.crypticle.dumps({})
        except IOError:
            log.error('AES key not found')
            return {'error': 'AES key not found'}

        pret = {}
        if not six.PY2:
            key = salt.utils.stringutils.to_bytes(key)
        if HAS_M2:
            pret['key'] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding)
        else:
            cipher = PKCS1_OAEP.new(pub)
            pret['key'] = cipher.encrypt(key)
        pret[dictkey] = pcrypt.dumps(
            ret if ret is not False else {}
        )
        return pret
1100560
function decryptJson(password, data) {
    var salt = new Buffer(data.salt, 'base64');
    return pbkdf2(password, salt, pbkdf2Iterations, pbkdf2KeyLen, pbkdf2Digest).then(function (key) {
        var iv = new Buffer(data.iv, 'base64');
        var decipher = crypto.createDecipheriv(cipherAlgorithm, key, iv);
        var tag = data.tag;
        if (tag) {
            decipher.setAuthTag(new Buffer(tag, 'base64'));
        }
        var value = decipher.update(data.value, 'base64', 'utf8');
        value += decipher.final('utf8');
        return value;
    }).then(JSON.parse);
}