Skip to content

Instantly share code, notes, and snippets.

@yurenchen000
Last active May 13, 2022 23:29
Show Gist options
  • Save yurenchen000/f1b7f61b9d2c7576d51357f33e8f702b to your computer and use it in GitHub Desktop.
Save yurenchen000/f1b7f61b9d2c7576d51357f33e8f702b to your computer and use it in GitHub Desktop.
base64 implement in awk & hexdump
#!/usr/bin/awk -f
# from https://sites.google.com/site/dannychouinard/Home/unix-linux-trinkets/little-utilities/base64-and-base85-encoding-awk-scripts
#
# compatible with busybox:
# no od, awk not print \0
function encode64() {
while( "hexdump -e ' \"%07.7_ax \" 16/1 \"%02x \" \"\n\"'" | getline ) {
for(c=9; c<=length($0); c++) {
d=index("0123456789abcdef",substr($0,c,1));
if(d--) {
for(b=1; b<=4; b++ ) {
o=o*2+int(d/8); d=(d*2)%16;
if(++obc==6) {
printf substr(b64,o+1,1);
if(++rc>75) { printf("\n"); rc=0; }
obc=0; o=0;
}
}
}
}
}
if(obc) {
while(obc++<6) { o=o*2; }
printf "%c",substr(b64,o+1,1);
}
print "==";
}
function putchar(c) {
if(c==0)
system("echo -ne \"\\00\"")
else
printf "%c",o;
}
function decode64() {
while( getline < "/dev/stdin" ) {
for(i=1;i<=length($0);i++) {
c=index(b64,substr($0,i,1));
if(c--) {
for(b=0;b<6;b++) {
o=o*2+int(c/32); c=(c*2)%64;
#printf "\n[%s]", o > "/dev/stderr";
if(++obc==8) { putchar(o); obc=0; o=0; }
}
}
}
}
}
BEGIN {
b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
if(ARGV[1]=="d") { decode64(); exit; }
encode64();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment