Skip to content

Instantly share code, notes, and snippets.

@jjenkins70
Last active July 17, 2024 08:19
Show Gist options
  • Save jjenkins70/957758d110dc63d8667dee1ee52e1939 to your computer and use it in GitHub Desktop.
Save jjenkins70/957758d110dc63d8667dee1ee52e1939 to your computer and use it in GitHub Desktop.
Vault Transit Secrets Example.

vault server --dev --dev-root-token-id="root" PreReq: export VAULT_ADDR=http://127.0.0.1:8200/ export VAULT_TOKEN=root

# Enable transit secrets engine
path "sys/mounts/transit" {
  capabilities = [ "create", "read", "update", "delete", "list" ]
}

# To read enabled secrets engines
path "sys/mounts" {
  capabilities = [ "read" ]
}

# Manage the transit secrets engine
path "transit/*" {
  capabilities = [ "create", "read", "update", "delete", "list" ]
}

vault policy write transit-policy - <<EOF

Enable transit secrets engine

path "sys/mounts/transit" { capabilities = [ "create", "read", "update", "delete", "list" ] }

To read enabled secrets engines

path "sys/mounts" { capabilities = [ "read" ] }

Manage the transit secrets engine

path "transit/*" { capabilities = [ "create", "read", "update", "delete", "list" ] } EOF

Create a file that needs to be encrypted.

echo “this is a sample file to be encrypted” | base64 > sample.txt cat sample.txt

Enable secrets engine:

vault secrets enable -path=transit transit

Create key pair called example-key

curl -k --header "X-Vault-Token: ${VAULT_TOKEN}" --request POST --data '{"exportable":"false","type":"rsa-4096"}' ${VAULT_ADDR}/v1/transit/keys/example-key

Verify by reading public key

curl -k --header "X-Vault-Token: ${VAULT_TOKEN}" --request GET ${VAULT_ADDR}/v1/transit/keys/example-key | jq . -note you can save this as publickey.pub

Here is a branch you can take to export private key - if required

Get private key (version 1) -- will not show since export now = false

curl -k --header "X-Vault-Token: ${VAULT_TOKEN}" --request GET ${VAULT_ADDR}/v1/transit/export/encryption-key/example-key | jq . CLI: vault read transit/keys/example-key

End branch

Create data signature

vault write transit/sign/example-key [email protected] -format=json | jq -r .data.signature > /tmp/signature

Encrypt

vault write transit/encrypt/example-key plaintext=$(cat sample.txt) -format=json | jq -r .data.ciphertext > /tmp/ciphertext

Decrypt

vault write transit/decrypt/example-key ciphertext=$(cat /tmp/ciphertext) -format=json | jq -r .data.plaintext|base64 -d

echo -n '{"ciphertext": "vault:v1:' > encryptedFile.txt cat sample.txt | openssl pkeyutl -encrypt -inkey publickkey.pub -pubin -pkeyopt rssa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 | base64 -w 0 | cat >> encryptedFile.txt; echo -n '"}' >> encryptedFile.txt

cat encryptedFile.txt | vault write -field=plaintext transit/decrypt/example-key - | base64 -d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment