Skip to content

Instantly share code, notes, and snippets.

@bcomnes
Created May 31, 2016 22:35
Show Gist options
  • Save bcomnes/4eb47c9df51cb5cbb8d54f7859a9b5d6 to your computer and use it in GitHub Desktop.
Save bcomnes/4eb47c9df51cb5cbb8d54f7859a9b5d6 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/base64"
"fmt"
"os"
"strings"
)
const (
FieldBase = 16 // size of the matrix
FieldSizeX = FieldBase + 1
FieldSizeY = 2*FieldBase + 1
)
func max(a, b int) int {
if a < b {
return b
}
return a
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
// RandomArt is the internal representation of a randomart image
type RandomArt [FieldSizeX][FieldSizeY]byte
// generate randomart matrix
// i have no idea what im doing. port of openssh randomart.
// https://github.com/openssh/openssh-portable/blob/271df8185d9689b3fb0523f58514481b858f6843/sshkey.c#L1051
func randomart(key []byte) RandomArt {
var innerLoop = [4]int{0, 1, 2, 3}
field := [FieldSizeX][FieldSizeY]byte{}
x, y := FieldSizeX/2, FieldSizeY/2
for _, input := range key {
for _ = range innerLoop {
switch input & 0x1 {
case 1:
x += 1
case 0:
x -= 1
}
switch input & 0x2 {
case 2:
y += 1
case 0:
y -= 1
}
/* assure we are still in bounds */
x = max(x, 0)
y = max(y, 0)
x = min(x, FieldSizeX-1)
y = min(y, FieldSizeY-1)
/* augment the field */
if int(field[x][y]) < len(key)-2 {
field[x][y]++
}
input = input >> 2
}
}
return field
}
//print colorized ssh-style randomart
func plot(art RandomArt, id string) {
syms := []string{
" ",
".",
"o",
"+",
"=",
"*",
"B",
"O",
"X", // maybe somebody wants to
"@", // add more color escapes?
"%", // i ran out of ideas for
"&", // the moment.
"#",
"/",
"^",
"S",
"E",
}
spaces := ""
for i := 0; i < (len(id)-FieldSizeY)/2-1; i++ {
spaces += " "
}
fmt.Println(id)
for _, line := range art {
fmt.Print(spaces + "|")
for _, char := range line {
fmt.Printf("%s", syms[char])
}
fmt.Println("|")
}
}
// print matlab surf command
func surf(art RandomArt) {
fmt.Println("% put this into matlab or octave")
fmt.Println("surf([")
for _, line := range art {
fmt.Print("[")
for _, char := range line {
fmt.Print(char, ",")
}
fmt.Println("];")
}
fmt.Println("]);")
}
func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: %s <id>\n", os.Args[0])
return
}
id := os.Args[1]
if id[0] != '@' || strings.Split(id[1:], ".")[1] != "ed25519" {
fmt.Println("error: that does not look like an id.")
return
}
b64Key := strings.Split(id[1:], ".")[0]
key, err := base64.StdEncoding.DecodeString(b64Key)
if err != nil {
fmt.Println("error parsing public key:", err)
return
}
art := randomart(key)
// plot(art, id)
surf(art)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment