Last active
August 29, 2015 14:17
-
-
Save kou1okada/249c6583ffe7f63c8e66 to your computer and use it in GitHub Desktop.
Encrypt file by AES256 and ssh ECDSA key pairs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Copyright (c) 2015 Koichi OKADA. All rights reserved. | |
# This script is destributed under the MIT license. | |
# | |
if (( $# != 3 )); then | |
cat <<EOD | |
Usage: $(basename $0) key peerkey file | |
Encrypt file by AES256 and ssh ECDSA key pairs. | |
key : ssh ecdsa private key | |
peerkey : ssh ecdsa public key | |
file : file that will be encrypted | |
EOD | |
exit 1 | |
fi | |
function get_decrypt_fn () | |
{ | |
local fn ext body | |
fn="$(basename "$1")" | |
body="${fn%.*}" | |
ext="${fn##*.}" | |
[ "$ext" = "$body" -o ".$ext" = "$body" ] && ext="" | |
[ -n "$ext" ] && ext=".$ext" | |
echo "${body}.decrypt${ext}" | |
} | |
key="$1" | |
pubkey="$(basename "${1}.pub.PKCS8")" | |
peerkey="${2}.PKCS8" | |
file="$3" | |
decryptfile="$(get_decrypt_fn "$file")" | |
keytype="$(ssh-keygen -vlf "$2" | awk 'match($0, /\(([0-9A-Za-z]+)\)$/, m){print m[1]; exit}')" | |
keylen="$(ssh-keygen -vlf "$2" | awk '{print $1; exit}')" | |
dir="encrypt.$(date +%Y%m%d_%H%M%S)" | |
[ -e "$1" ] || ssh-keygen -f "$1" -t "$keytype" -b "$keylen" | |
[ -e "$pubkey" ] || ssh-keygen -f "${1}.pub" -e -m PKCS8 > "$pubkey" | |
[ -e "$peerkey" ] || ssh-keygen -f "$2" -e -m PKCS8 > "$peerkey" | |
[ -e "$dir" ] || mkdir "$dir" | |
openssl pkeyutl -derive -inkey "$1" -peerkey "$peerkey" | openssl enc -e -aes256 -in "$file" -out "${dir}/${file}.aes256" -pass stdin | |
cp "$pubkey" "${dir}/" | |
echo "for decrypt" | |
echo 'openssl pkeyutl -derive -inkey "~/.ssh/'${2%.*}'" -peerkey "'$pubkey'" | openssl enc -d -aes256 -in "'${file}.aes256'" -out "'${decryptfile}'" -pass stdin' | tee "${dir}/decrpyt.txt" | |
echo "for decrypt test" | |
echo 'openssl pkeyutl -derive -inkey "'$1'" -peerkey "'$peerkey'" | openssl enc -d -aes256 -in "'${dir}/${file}.aes256'" -out "'${decryptfile}'" -pass stdin' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment