November 5, 2013

SNMP V3 password to key algorithm implementation in GoLang

package main
import (
    "fmt"
    "io"
    "crypto/md5"
    "crypto/sha1"
)

func  password_to_key( password string, engineID string, hash_alg string) {
        h := sha1.New()
        if hash_alg=="MD5" {
                h = md5.New()
        }

        count := 0;
        plen:=len(password);
        repeat := 1048576/plen;
        remain := 1048576%plen;
        for count < repeat {
                io.WriteString(h,password);
                count++;
        }
        if remain > 0 {
                io.WriteString(h,string(password[:remain]));
        }
        ku := string(h.Sum(nil))
        fmt.Printf("ku=% x\n", ku)

        h.Reset();
        io.WriteString(h,ku);
        io.WriteString(h,engineID);
        io.WriteString(h,ku);
        localKey:=h.Sum(nil);
        fmt.Printf("localKey=% x\n", localKey)

        return;
}

func main(){
        password_to_key("maplesyrup","\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02","MD5");
        password_to_key("maplesyrup","\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02","SHA1");
}

No comments:

Post a Comment