kunt

golang IRC bot
git clone git@git.2f30.org/kunt.git
Log | Files | Refs | LICENSE

benc.go (1205B)


      1 package main
      2 
      3 import (
      4 	"code.google.com/p/go.crypto/blowfish"
      5 	"encoding/gob"
      6 	"flag"
      7 	"fmt"
      8 	"io/ioutil"
      9 	"log"
     10 	"os"
     11 )
     12 
     13 func usage() {
     14 	fmt.Fprintf(os.Stderr, "usage: %s <pass> <file>\n",
     15 		os.Args[0])
     16 	os.Exit(2)
     17 }
     18 
     19 func encryptBuf(c *blowfish.Cipher, a []byte) []byte {
     20 	padded := a
     21 	diff := len(a) % blowfish.BlockSize
     22 	if diff != 0 {
     23 		diff = blowfish.BlockSize - diff
     24 	}
     25 	for i := 0; i < diff; i++ {
     26 		padded = append(padded, byte(0x0))
     27 	}
     28 	ct := make([]byte, len(padded))
     29 	for i := 0; i < len(a); i += blowfish.BlockSize {
     30 		if i+blowfish.BlockSize > len(a) {
     31 			c.Encrypt(ct[i:], padded[i:])
     32 			return ct
     33 		}
     34 		c.Encrypt(ct[i:i+blowfish.BlockSize],
     35 			padded[i:i+blowfish.BlockSize])
     36 	}
     37 	return ct
     38 }
     39 
     40 type hdr struct {
     41 	Magic string
     42 	Len   int
     43 	Data  []byte
     44 }
     45 
     46 func main() {
     47 	log.SetPrefix("benc: ")
     48 	flag.Usage = usage
     49 	flag.Parse()
     50 
     51 	args := flag.Args()
     52 	if len(args) < 2 {
     53 		usage()
     54 	}
     55 
     56 	c, err := blowfish.NewCipher([]byte(args[0]))
     57 	if err != nil {
     58 		log.Fatal(err)
     59 	}
     60 
     61 	b, err := ioutil.ReadFile(args[1])
     62 	if err != nil {
     63 		log.Fatal(err)
     64 	}
     65 	eb := encryptBuf(c, b)
     66 
     67 	h := &hdr{"BENC", len(b), eb}
     68 	g := gob.NewEncoder(os.Stdout)
     69 	err = g.Encode(*h)
     70 	if err != nil {
     71 		log.Fatal(err)
     72 	}
     73 }