Skip to content

Instantly share code, notes, and snippets.

@kafaa-dev
Created November 28, 2024 04:38
Show Gist options
  • Save kafaa-dev/2071979a4a16ab72778380388e07f64b to your computer and use it in GitHub Desktop.
Save kafaa-dev/2071979a4a16ab72778380388e07f64b to your computer and use it in GitHub Desktop.
Export pass to JSON.

Goal

The goal was to export all of the passwords stored using pass to JSON format.

Warning

Warning

May contain bugs. This code was written with a focus on the result, and it worked for me.

Why did I focus on the result and not worry about other cases? Because when I wrote this, I just wanted to get the job done.

And recently, I realized that "I wanted to do X by doing this and that so blablabla" was just my excuse to delay a job.

Also, this is one of the reasons I love PHP. It allows you to write almost anything, from simple scripts to complex things.

Background

Several months ago, I switched to using Bitwarden for managing my passwords because it is cross-platform and accessible via a web browser.

And because of some reasons, I don't have the time to migrate it manually.

I created this script so that I can at least uninstall pass and be able to migrate my passwords later.


I share the code because it may useful for someone (and for my future self maybe? hmm).

<?php
define('PASSWORD_STORE_DIRECTORY', $_SERVER['HOME'] . '/.password-store');
define('PASSWORD_STORE_DIRECTORY_LENGTH', strlen(PASSWORD_STORE_DIRECTORY));
/**
* @return string[]
*/
function getPasswordNames(): array {
$passwords = [];
$directoryIterator = new RecursiveDirectoryIterator(PASSWORD_STORE_DIRECTORY);
$recursiveIterator = new RecursiveIteratorIterator($directoryIterator);
$regexIterator = new RegexIterator($recursiveIterator, '/\.gpg$/');
foreach ($regexIterator as $passwordFile) {
/** @var SplFileInfo $passwordFile */
$passwords[] = substr($passwordFile->getPathname(), PASSWORD_STORE_DIRECTORY_LENGTH + 1, -4);
}
return $passwords;
}
function getPassword(string $name): string {
return shell_exec('pass show ' . escapeshellarg($name));
}
/**
* @return array{name:string,password:string}[]
*/
function getPasswords(): array {
$passwordNames = getPasswordNames();
$passwords = [];
foreach ($passwordNames as $passwordName) {
$password = getPassword($passwordName);
$passwords[] = [
'name' => $passwordName,
'password' => $password,
];
}
return $passwords;
}
echo json_encode(getPasswords(), JSON_PRETTY_PRINT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment