format with go fmt

This commit is contained in:
Jeff Becker
2016-01-29 07:22:31 -05:00
parent f2c6e01206
commit 1e471e4e00
38 changed files with 694 additions and 729 deletions

View File

@ -4,15 +4,14 @@
package base32 package base32
import ( import (
b32 "encoding/base32" b32 "encoding/base32"
) )
// i2p base32 encoding // i2p base32 encoding
var I2PEncoding *b32.Encoding = b32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567") var I2PEncoding *b32.Encoding = b32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567")
// wrapper arround encoding for encoding to string // wrapper arround encoding for encoding to string
func EncodeToString(data []byte) (str string) { func EncodeToString(data []byte) (str string) {
str = I2PEncoding.EncodeToString(data) str = I2PEncoding.EncodeToString(data)
return return
} }

View File

@ -4,7 +4,7 @@
package base64 package base64
import ( import (
b64 "encoding/base64" b64 "encoding/base64"
) )
// i2p base64 encoding // i2p base64 encoding
@ -12,6 +12,6 @@ var I2PEncoding *b64.Encoding = b64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcde
// wrapper arround encoding for encoding to string // wrapper arround encoding for encoding to string
func EncodeToString(data []byte) (str string) { func EncodeToString(data []byte) (str string) {
str = I2PEncoding.EncodeToString(data) str = I2PEncoding.EncodeToString(data)
return return
} }

View File

@ -1,5 +1,4 @@
package common package common
// the sha256 of some datastructure // the sha256 of some datastructure
type IdentHash [32]byte type IdentHash [32]byte

View File

@ -1,14 +1,14 @@
package common package common
import ( import (
"os" "os"
) )
// check if a file is there and writeable // check if a file is there and writeable
func FileExists(fname string) (exists bool) { func FileExists(fname string) (exists bool) {
_, err := os.Stat(fname) _, err := os.Stat(fname)
if err == nil { if err == nil {
exists = true exists = true
} }
return return
} }

View File

@ -1,6 +1,5 @@
package config package config
type BootstrapConfig struct { type BootstrapConfig struct {
LowPeerThreshold int LowPeerThreshold int
} }

View File

@ -2,12 +2,12 @@ package config
// router.config options // router.config options
type RouterConfig struct { type RouterConfig struct {
NetDbDir string NetDbDir string
Bootstrap BootstrapConfig Bootstrap BootstrapConfig
} }
// defaults for router // defaults for router
var Router = &RouterConfig{ var Router = &RouterConfig{
NetDbDir: "./netDb", NetDbDir: "./netDb",
} }

View File

@ -2,14 +2,14 @@ package crypto
// decrypts data // decrypts data
type Decrypter interface { type Decrypter interface {
// decrypt a block of data // decrypt a block of data
// return decrypted block or nil and error if error happens // return decrypted block or nil and error if error happens
Decrypt(data []byte) ([]byte, error) Decrypt(data []byte) ([]byte, error)
} }
type PrivateEncryptionKey interface { type PrivateEncryptionKey interface {
// create a new decryption object for this private key to decrypt data encrypted to our public key // create a new decryption object for this private key to decrypt data encrypted to our public key
// returns decrypter or nil and error if the private key is in a bad format // returns decrypter or nil and error if the private key is in a bad format
NewDecrypter() (Decrypter, error) NewDecrypter() (Decrypter, error)
} }

View File

@ -1,152 +1,150 @@
package crypto package crypto
import ( import (
"crypto/dsa" "crypto/dsa"
"crypto/sha1" "crypto/rand"
"crypto/rand" "crypto/sha1"
"io" "io"
"math/big" "math/big"
) )
var dsap = new(big.Int).SetBytes([]byte{ var dsap = new(big.Int).SetBytes([]byte{
0x9c, 0x05, 0xb2, 0xaa, 0x96, 0x0d, 0x9b, 0x97, 0xb8, 0x93, 0x19, 0x63, 0xc9, 0xcc, 0x9e, 0x8c, 0x9c, 0x05, 0xb2, 0xaa, 0x96, 0x0d, 0x9b, 0x97, 0xb8, 0x93, 0x19, 0x63, 0xc9, 0xcc, 0x9e, 0x8c,
0x30, 0x26, 0xe9, 0xb8, 0xed, 0x92, 0xfa, 0xd0, 0xa6, 0x9c, 0xc8, 0x86, 0xd5, 0xbf, 0x80, 0x15, 0x30, 0x26, 0xe9, 0xb8, 0xed, 0x92, 0xfa, 0xd0, 0xa6, 0x9c, 0xc8, 0x86, 0xd5, 0xbf, 0x80, 0x15,
0xfc, 0xad, 0xae, 0x31, 0xa0, 0xad, 0x18, 0xfa, 0xb3, 0xf0, 0x1b, 0x00, 0xa3, 0x58, 0xde, 0x23, 0xfc, 0xad, 0xae, 0x31, 0xa0, 0xad, 0x18, 0xfa, 0xb3, 0xf0, 0x1b, 0x00, 0xa3, 0x58, 0xde, 0x23,
0x76, 0x55, 0xc4, 0x96, 0x4a, 0xfa, 0xa2, 0xb3, 0x37, 0xe9, 0x6a, 0xd3, 0x16, 0xb9, 0xfb, 0x1c, 0x76, 0x55, 0xc4, 0x96, 0x4a, 0xfa, 0xa2, 0xb3, 0x37, 0xe9, 0x6a, 0xd3, 0x16, 0xb9, 0xfb, 0x1c,
0xc5, 0x64, 0xb5, 0xae, 0xc5, 0xb6, 0x9a, 0x9f, 0xf6, 0xc3, 0xe4, 0x54, 0x87, 0x07, 0xfe, 0xf8, 0xc5, 0x64, 0xb5, 0xae, 0xc5, 0xb6, 0x9a, 0x9f, 0xf6, 0xc3, 0xe4, 0x54, 0x87, 0x07, 0xfe, 0xf8,
0x50, 0x3d, 0x91, 0xdd, 0x86, 0x02, 0xe8, 0x67, 0xe6, 0xd3, 0x5d, 0x22, 0x35, 0xc1, 0x86, 0x9c, 0x50, 0x3d, 0x91, 0xdd, 0x86, 0x02, 0xe8, 0x67, 0xe6, 0xd3, 0x5d, 0x22, 0x35, 0xc1, 0x86, 0x9c,
0xe2, 0x47, 0x9c, 0x3b, 0x9d, 0x54, 0x01, 0xde, 0x04, 0xe0, 0x72, 0x7f, 0xb3, 0x3d, 0x65, 0x11, 0xe2, 0x47, 0x9c, 0x3b, 0x9d, 0x54, 0x01, 0xde, 0x04, 0xe0, 0x72, 0x7f, 0xb3, 0x3d, 0x65, 0x11,
0x28, 0x5d, 0x4c, 0xf2, 0x95, 0x38, 0xd9, 0xe3, 0xb6, 0x05, 0x1f, 0x5b, 0x22, 0xcc, 0x1c, 0x93, 0x28, 0x5d, 0x4c, 0xf2, 0x95, 0x38, 0xd9, 0xe3, 0xb6, 0x05, 0x1f, 0x5b, 0x22, 0xcc, 0x1c, 0x93,
}) })
var dsaq = new(big.Int).SetBytes([]byte{ var dsaq = new(big.Int).SetBytes([]byte{
0xa5, 0xdf, 0xc2, 0x8f, 0xef, 0x4c, 0xa1, 0xe2, 0x86, 0x74, 0x4c, 0xd8, 0xee, 0xd9, 0xd2, 0x9d, 0xa5, 0xdf, 0xc2, 0x8f, 0xef, 0x4c, 0xa1, 0xe2, 0x86, 0x74, 0x4c, 0xd8, 0xee, 0xd9, 0xd2, 0x9d,
0x68, 0x40, 0x46, 0xb7, 0x68, 0x40, 0x46, 0xb7,
}); })
var dsag = new(big.Int).SetBytes([]byte{ var dsag = new(big.Int).SetBytes([]byte{
0x0c, 0x1f, 0x4d, 0x27, 0xd4, 0x00, 0x93, 0xb4, 0x29, 0xe9, 0x62, 0xd7, 0x22, 0x38, 0x24, 0xe0, 0x0c, 0x1f, 0x4d, 0x27, 0xd4, 0x00, 0x93, 0xb4, 0x29, 0xe9, 0x62, 0xd7, 0x22, 0x38, 0x24, 0xe0,
0xbb, 0xc4, 0x7e, 0x7c, 0x83, 0x2a, 0x39, 0x23, 0x6f, 0xc6, 0x83, 0xaf, 0x84, 0x88, 0x95, 0x81, 0xbb, 0xc4, 0x7e, 0x7c, 0x83, 0x2a, 0x39, 0x23, 0x6f, 0xc6, 0x83, 0xaf, 0x84, 0x88, 0x95, 0x81,
0x07, 0x5f, 0xf9, 0x08, 0x2e, 0xd3, 0x23, 0x53, 0xd4, 0x37, 0x4d, 0x73, 0x01, 0xcd, 0xa1, 0xd2, 0x07, 0x5f, 0xf9, 0x08, 0x2e, 0xd3, 0x23, 0x53, 0xd4, 0x37, 0x4d, 0x73, 0x01, 0xcd, 0xa1, 0xd2,
0x3c, 0x43, 0x1f, 0x46, 0x98, 0x59, 0x9d, 0xda, 0x02, 0x45, 0x18, 0x24, 0xff, 0x36, 0x97, 0x52, 0x3c, 0x43, 0x1f, 0x46, 0x98, 0x59, 0x9d, 0xda, 0x02, 0x45, 0x18, 0x24, 0xff, 0x36, 0x97, 0x52,
0x59, 0x36, 0x47, 0xcc, 0x3d, 0xdc, 0x19, 0x7d, 0xe9, 0x85, 0xe4, 0x3d, 0x13, 0x6c, 0xdc, 0xfc, 0x59, 0x36, 0x47, 0xcc, 0x3d, 0xdc, 0x19, 0x7d, 0xe9, 0x85, 0xe4, 0x3d, 0x13, 0x6c, 0xdc, 0xfc,
0x6b, 0xd5, 0x40, 0x9c, 0xd2, 0xf4, 0x50, 0x82, 0x11, 0x42, 0xa5, 0xe6, 0xf8, 0xeb, 0x1c, 0x3a, 0x6b, 0xd5, 0x40, 0x9c, 0xd2, 0xf4, 0x50, 0x82, 0x11, 0x42, 0xa5, 0xe6, 0xf8, 0xeb, 0x1c, 0x3a,
0xb5, 0xd0, 0x48, 0x4b, 0x81, 0x29, 0xfc, 0xf1, 0x7b, 0xce, 0x4f, 0x7f, 0x33, 0x32, 0x1c, 0x3c, 0xb5, 0xd0, 0x48, 0x4b, 0x81, 0x29, 0xfc, 0xf1, 0x7b, 0xce, 0x4f, 0x7f, 0x33, 0x32, 0x1c, 0x3c,
0xb3, 0xdb, 0xb1, 0x4a, 0x90, 0x5e, 0x7b, 0x2b, 0x3e, 0x93, 0xbe, 0x47, 0x08, 0xcb, 0xcc, 0x82, 0xb3, 0xdb, 0xb1, 0x4a, 0x90, 0x5e, 0x7b, 0x2b, 0x3e, 0x93, 0xbe, 0x47, 0x08, 0xcb, 0xcc, 0x82,
}); })
var param = dsa.Parameters{ var param = dsa.Parameters{
P: dsap, P: dsap,
Q: dsaq, Q: dsaq,
G: dsag, G: dsag,
} }
// generate a dsa keypair // generate a dsa keypair
func DSAGenerate(priv *dsa.PrivateKey, rand io.Reader) error { func DSAGenerate(priv *dsa.PrivateKey, rand io.Reader) error {
// put our paramters in // put our paramters in
priv.P = param.P priv.P = param.P
priv.Q = param.Q priv.Q = param.Q
priv.G = param.G priv.G = param.G
// generate the keypair // generate the keypair
return dsa.GenerateKey(priv, rand) return dsa.GenerateKey(priv, rand)
} }
// create i2p dsa public key given its public component // create i2p dsa public key given its public component
func createDSAPublicKey(Y *big.Int) *dsa.PublicKey { func createDSAPublicKey(Y *big.Int) *dsa.PublicKey {
return &dsa.PublicKey{ return &dsa.PublicKey{
Parameters: param, Parameters: param,
Y: Y, Y: Y,
} }
} }
// createa i2p dsa private key given its public component // createa i2p dsa private key given its public component
func createDSAPrivkey(X *big.Int) *dsa.PrivateKey { func createDSAPrivkey(X *big.Int) *dsa.PrivateKey {
Y := new(big.Int) Y := new(big.Int)
Y.Exp(dsag, X, dsap) Y.Exp(dsag, X, dsap)
return &dsa.PrivateKey{ return &dsa.PrivateKey{
PublicKey: dsa.PublicKey{ PublicKey: dsa.PublicKey{
Parameters: param, Parameters: param,
Y: Y, Y: Y,
}, },
X: X, X: X,
} }
} }
type DSAVerifier struct { type DSAVerifier struct {
k *dsa.PublicKey k *dsa.PublicKey
} }
type DSAPublicKey [128]byte type DSAPublicKey [128]byte
// create a new dsa verifier // create a new dsa verifier
func (k DSAPublicKey) NewVerifier() (v Verifier, err error) { func (k DSAPublicKey) NewVerifier() (v Verifier, err error) {
v = &DSAVerifier{ v = &DSAVerifier{
k: createDSAPublicKey(new(big.Int).SetBytes(k[:])), k: createDSAPublicKey(new(big.Int).SetBytes(k[:])),
} }
return return
} }
// verify data with a dsa public key // verify data with a dsa public key
func (v *DSAVerifier) Verify(data, sig []byte) (err error) { func (v *DSAVerifier) Verify(data, sig []byte) (err error) {
h := sha1.Sum(data) h := sha1.Sum(data)
err = v.VerifyHash(h[:], sig) err = v.VerifyHash(h[:], sig)
return return
} }
// verify hash of data with a dsa public key // verify hash of data with a dsa public key
func (v *DSAVerifier) VerifyHash(h, sig []byte) (err error) { func (v *DSAVerifier) VerifyHash(h, sig []byte) (err error) {
if len(sig) == 40 { if len(sig) == 40 {
r := new(big.Int).SetBytes(sig[:20]) r := new(big.Int).SetBytes(sig[:20])
s := new(big.Int).SetBytes(sig[20:]) s := new(big.Int).SetBytes(sig[20:])
if dsa.Verify(v.k, h, r, s) { if dsa.Verify(v.k, h, r, s) {
// valid signature // valid signature
} else { } else {
// invalid signature // invalid signature
err = ErrInvalidSignature err = ErrInvalidSignature
} }
} else { } else {
err = ErrBadSignatureSize err = ErrBadSignatureSize
} }
return return
} }
func (k DSAPublicKey) Len() int { func (k DSAPublicKey) Len() int {
return len(k) return len(k)
} }
type DSASigner struct { type DSASigner struct {
k *dsa.PrivateKey k *dsa.PrivateKey
} }
type DSAPrivateKey [20]byte type DSAPrivateKey [20]byte
// create a new dsa signer // create a new dsa signer
func (k DSAPrivateKey) NewSigner() (s Signer, err error) { func (k DSAPrivateKey) NewSigner() (s Signer, err error) {
s = &DSASigner{ s = &DSASigner{
k: createDSAPrivkey(new (big.Int).SetBytes(k[:])), k: createDSAPrivkey(new(big.Int).SetBytes(k[:])),
} }
return return
} }
func (ds *DSASigner) Sign(data []byte) (sig []byte, err error) { func (ds *DSASigner) Sign(data []byte) (sig []byte, err error) {
h := sha1.Sum(data) h := sha1.Sum(data)
sig, err = ds.SignHash(h[:]) sig, err = ds.SignHash(h[:])
return return
} }
func (ds *DSASigner) SignHash(h []byte) (sig []byte, err error) { func (ds *DSASigner) SignHash(h []byte) (sig []byte, err error) {
var r, s *big.Int var r, s *big.Int
r, s, err = dsa.Sign(rand.Reader, ds.k, h) r, s, err = dsa.Sign(rand.Reader, ds.k, h)
if err == nil { if err == nil {
sig = make([]byte, 40) sig = make([]byte, 40)
copy(sig, r.Bytes()) copy(sig, r.Bytes())
copy(sig[20:], s.Bytes()) copy(sig[20:], s.Bytes())
} }
return return
} }
func (k DSAPrivateKey) Len() int { func (k DSAPrivateKey) Len() int {
return len(k) return len(k)
} }

View File

@ -1,28 +1,27 @@
package crypto package crypto
import ( import (
"crypto/dsa" "crypto/dsa"
"crypto/rand" "crypto/rand"
"testing" "testing"
) )
func TestDSA(t *testing.T) { func TestDSA(t *testing.T) {
rng := rand.Reader rng := rand.Reader
kp := new(dsa.PrivateKey) kp := new(dsa.PrivateKey)
err := DSAGenerate(kp, rng) err := DSAGenerate(kp, rng)
if err == nil { if err == nil {
t.Logf("DSA Key Pair generated") t.Logf("DSA Key Pair generated")
} else { } else {
t.Logf("error while generating key: %s", err) t.Logf("error while generating key: %s", err)
t.Fail() t.Fail()
} }
h := make([]byte, 20) h := make([]byte, 20)
_, _, err = dsa.Sign(rng, kp, h) _, _, err = dsa.Sign(rng, kp, h)
if err == nil { if err == nil {
t.Log("signed") t.Log("signed")
} else { } else {
t.Logf("error signing: %s", err) t.Logf("error signing: %s", err)
t.Fail() t.Fail()
} }
} }

View File

@ -1,78 +1,78 @@
package crypto package crypto
import ( import (
"crypto" "crypto"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic" "crypto/elliptic"
) )
type ECDSAVerifier struct { type ECDSAVerifier struct {
k *ecdsa.PublicKey k *ecdsa.PublicKey
c elliptic.Curve c elliptic.Curve
h crypto.Hash h crypto.Hash
} }
// verify a signature given the hash // verify a signature given the hash
func (v *ECDSAVerifier) VerifyHash(h, sig []byte) (err error) { func (v *ECDSAVerifier) VerifyHash(h, sig []byte) (err error) {
r, s := elliptic.Unmarshal(v.c, sig) r, s := elliptic.Unmarshal(v.c, sig)
if r == nil || s == nil || ! ecdsa.Verify(v.k, h, r, s) { if r == nil || s == nil || !ecdsa.Verify(v.k, h, r, s) {
err = ErrInvalidSignature err = ErrInvalidSignature
} }
return return
} }
// verify a block of data by hashing it and comparing the hash against the signature // verify a block of data by hashing it and comparing the hash against the signature
func (v *ECDSAVerifier) Verify(data, sig []byte) (err error) { func (v *ECDSAVerifier) Verify(data, sig []byte) (err error) {
// sum the data and get the hash // sum the data and get the hash
h := v.h.New().Sum(data)[len(data):] h := v.h.New().Sum(data)[len(data):]
// verify // verify
err = v.VerifyHash(h, sig) err = v.VerifyHash(h, sig)
return return
} }
func createECVerifier(c elliptic.Curve, h crypto.Hash, k []byte) (ev *ECDSAVerifier, err error) { func createECVerifier(c elliptic.Curve, h crypto.Hash, k []byte) (ev *ECDSAVerifier, err error) {
x, y := elliptic.Unmarshal(c, k[:]) x, y := elliptic.Unmarshal(c, k[:])
if x == nil { if x == nil {
err = ErrInvalidKeyFormat err = ErrInvalidKeyFormat
} else { } else {
ev = &ECDSAVerifier{ ev = &ECDSAVerifier{
c: c, c: c,
h: h, h: h,
} }
ev.k = &ecdsa.PublicKey{c, x, y} ev.k = &ecdsa.PublicKey{c, x, y}
} }
return return
} }
type ECP256PublicKey [64]byte type ECP256PublicKey [64]byte
type ECP256PrivateKey [32]byte type ECP256PrivateKey [32]byte
func (k ECP256PublicKey) Len() int { func (k ECP256PublicKey) Len() int {
return len(k) return len(k)
} }
func (k ECP256PublicKey) NewVerifier() (Verifier, error) { func (k ECP256PublicKey) NewVerifier() (Verifier, error) {
return createECVerifier(elliptic.P256(), crypto.SHA256, k[:]) return createECVerifier(elliptic.P256(), crypto.SHA256, k[:])
} }
type ECP384PublicKey [96]byte type ECP384PublicKey [96]byte
type ECP384PrivateKey [48]byte type ECP384PrivateKey [48]byte
func (k ECP384PublicKey) Len() int { func (k ECP384PublicKey) Len() int {
return len(k) return len(k)
} }
func (k ECP384PublicKey) NewVerifier() (Verifier, error) { func (k ECP384PublicKey) NewVerifier() (Verifier, error) {
return createECVerifier(elliptic.P384(), crypto.SHA384, k[:]) return createECVerifier(elliptic.P384(), crypto.SHA384, k[:])
} }
type ECP521PublicKey [132]byte type ECP521PublicKey [132]byte
type ECP521PrivateKey [66]byte type ECP521PrivateKey [66]byte
func (k ECP521PublicKey) Len() int { func (k ECP521PublicKey) Len() int {
return len(k) return len(k)
} }
func (k ECP521PublicKey) NewVerifier() (Verifier, error) { func (k ECP521PublicKey) NewVerifier() (Verifier, error) {
return createECVerifier(elliptic.P521(), crypto.SHA512, k[:]) return createECVerifier(elliptic.P521(), crypto.SHA512, k[:])
} }

View File

@ -1,5 +1,4 @@
package crypto package crypto
type Ed25519PublicKey [32]byte type Ed25519PublicKey [32]byte
type Ed25519PrivateKey [32]byte type Ed25519PrivateKey [32]byte

View File

@ -1,32 +1,32 @@
package crypto package crypto
import ( import (
"crypto/rand" "crypto/rand"
"crypto/sha256" "crypto/sha256"
"crypto/subtle" "crypto/subtle"
"errors" "errors"
"golang.org/x/crypto/openpgp/elgamal" "golang.org/x/crypto/openpgp/elgamal"
"io" "io"
"math/big" "math/big"
) )
var elgp = new(big.Int).SetBytes([]byte{ var elgp = new(big.Int).SetBytes([]byte{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
}) })
var one = big.NewInt(1) var one = big.NewInt(1)
@ -37,175 +37,172 @@ var ElgEncryptTooBig = errors.New("failed to encrypt data, too big for elgamal")
// generate an elgamal key pair // generate an elgamal key pair
func ElgamalGenerate(priv *elgamal.PrivateKey, rand io.Reader) (err error) { func ElgamalGenerate(priv *elgamal.PrivateKey, rand io.Reader) (err error) {
priv.P = elgp priv.P = elgp
priv.G = elgg priv.G = elgg
xBytes := make([]byte, priv.P.BitLen()/8) xBytes := make([]byte, priv.P.BitLen()/8)
_, err = io.ReadFull(rand, xBytes) _, err = io.ReadFull(rand, xBytes)
if err == nil { if err == nil {
// set private key // set private key
priv.X = new(big.Int).SetBytes(xBytes) priv.X = new(big.Int).SetBytes(xBytes)
// compute public key // compute public key
priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P) priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P)
} }
return return
} }
type elgDecrypter struct { type elgDecrypter struct {
k *elgamal.PrivateKey k *elgamal.PrivateKey
} }
func (elg *elgDecrypter) Decrypt(data []byte) (dec []byte, err error) { func (elg *elgDecrypter) Decrypt(data []byte) (dec []byte, err error) {
dec, err = elgamalDecrypt(elg.k , data, true) // TODO(psi): should this be true or false? dec, err = elgamalDecrypt(elg.k, data, true) // TODO(psi): should this be true or false?
return return
} }
// decrypt an elgamal encrypted message, i2p style // decrypt an elgamal encrypted message, i2p style
func elgamalDecrypt(priv *elgamal.PrivateKey, data []byte, zeroPadding bool) (decrypted []byte, err error) { func elgamalDecrypt(priv *elgamal.PrivateKey, data []byte, zeroPadding bool) (decrypted []byte, err error) {
a := new(big.Int) a := new(big.Int)
b := new(big.Int) b := new(big.Int)
idx := 0 idx := 0
if zeroPadding { if zeroPadding {
idx ++ idx++
} }
a.SetBytes(data[idx : idx + 256]) a.SetBytes(data[idx : idx+256])
if zeroPadding { if zeroPadding {
idx ++ idx++
} }
b.SetBytes(data[idx + 256:]) b.SetBytes(data[idx+256:])
// decrypt // decrypt
m := new(big.Int).Mod(new(big.Int).Mul(b, new(big.Int).Exp(a,new(big.Int).Sub(new(big.Int).Sub(priv.P, priv.X), one), priv.P)), priv.P).Bytes() m := new(big.Int).Mod(new(big.Int).Mul(b, new(big.Int).Exp(a, new(big.Int).Sub(new(big.Int).Sub(priv.P, priv.X), one), priv.P)), priv.P).Bytes()
// check digest // check digest
d := sha256.Sum256(m[33:255]) d := sha256.Sum256(m[33:255])
good := 0 good := 0
if subtle.ConstantTimeCompare(d[:], m[1:33]) == 1 { if subtle.ConstantTimeCompare(d[:], m[1:33]) == 1 {
// decryption successful // decryption successful
good = 1 good = 1
} else { } else {
// decrypt failed // decrypt failed
err = ElgDecryptFail err = ElgDecryptFail
} }
// copy result // copy result
decrypted = make([]byte, 222) decrypted = make([]byte, 222)
subtle.ConstantTimeCopy(good, decrypted, m[33:255]) subtle.ConstantTimeCopy(good, decrypted, m[33:255])
if good == 0 { if good == 0 {
// if decrypt failed nil out decrypted slice // if decrypt failed nil out decrypted slice
decrypted = nil decrypted = nil
} }
return return
} }
type ElgamalEncryption struct { type ElgamalEncryption struct {
p, a, b1 *big.Int p, a, b1 *big.Int
} }
func (elg *ElgamalEncryption) Encrypt(data []byte) (enc []byte, err error) { func (elg *ElgamalEncryption) Encrypt(data []byte) (enc []byte, err error) {
return elg.EncryptPadding(data, true) return elg.EncryptPadding(data, true)
} }
func (elg *ElgamalEncryption) EncryptPadding(data []byte, zeroPadding bool) (encrypted []byte, err error) { func (elg *ElgamalEncryption) EncryptPadding(data []byte, zeroPadding bool) (encrypted []byte, err error) {
if len(data) > 222 { if len(data) > 222 {
err = ElgEncryptTooBig err = ElgEncryptTooBig
return return
} }
mbytes := make([]byte, 255) mbytes := make([]byte, 255)
mbytes[0] = 0xFF mbytes[0] = 0xFF
copy(mbytes[33:], data) copy(mbytes[33:], data)
// do sha256 of payload // do sha256 of payload
d := sha256.Sum256(mbytes[33:len(data)+33]) d := sha256.Sum256(mbytes[33 : len(data)+33])
copy(mbytes[1:], d[:]) copy(mbytes[1:], d[:])
m := new(big.Int).SetBytes(mbytes) m := new(big.Int).SetBytes(mbytes)
// do encryption // do encryption
b := new(big.Int).Mod(new(big.Int).Mul(elg.b1, m), elg.p).Bytes() b := new(big.Int).Mod(new(big.Int).Mul(elg.b1, m), elg.p).Bytes()
if zeroPadding { if zeroPadding {
encrypted = make([]byte, 514) encrypted = make([]byte, 514)
copy(encrypted[1:], elg.a.Bytes()) copy(encrypted[1:], elg.a.Bytes())
copy(encrypted[258:], b) copy(encrypted[258:], b)
} else { } else {
encrypted = make([]byte, 512) encrypted = make([]byte, 512)
copy(encrypted, elg.a.Bytes()) copy(encrypted, elg.a.Bytes())
copy(encrypted[256:], b) copy(encrypted[256:], b)
} }
return return
} }
// create an elgamal public key from byte slice // create an elgamal public key from byte slice
func createElgamalPublicKey(data []byte) (k *elgamal.PublicKey) { func createElgamalPublicKey(data []byte) (k *elgamal.PublicKey) {
if len(data) == 256 { if len(data) == 256 {
k = &elgamal.PublicKey{ k = &elgamal.PublicKey{
G: elgg, G: elgg,
P: elgp, P: elgp,
Y: new(big.Int).SetBytes(data), Y: new(big.Int).SetBytes(data),
} }
} }
return return
} }
// create an elgamal private key from byte slice // create an elgamal private key from byte slice
func createElgamalPrivateKey(data []byte) (k *elgamal.PrivateKey) { func createElgamalPrivateKey(data []byte) (k *elgamal.PrivateKey) {
if len(data) == 256 { if len(data) == 256 {
x := new(big.Int).SetBytes(data) x := new(big.Int).SetBytes(data)
y := new(big.Int).Exp(elgg, x, elgp) y := new(big.Int).Exp(elgg, x, elgp)
k = &elgamal.PrivateKey{ k = &elgamal.PrivateKey{
PublicKey: elgamal.PublicKey{ PublicKey: elgamal.PublicKey{
Y: y, Y: y,
G: elgg, G: elgg,
P: elgp, P: elgp,
}, },
X: x, X: x,
} }
} }
return return
} }
// create a new elgamal encryption session // create a new elgamal encryption session
func createElgamalEncryption(pub *elgamal.PublicKey, rand io.Reader) (enc *ElgamalEncryption, err error) { func createElgamalEncryption(pub *elgamal.PublicKey, rand io.Reader) (enc *ElgamalEncryption, err error) {
kbytes := make([]byte, 256) kbytes := make([]byte, 256)
k := new(big.Int) k := new(big.Int)
for err == nil { for err == nil {
_, err = io.ReadFull(rand, kbytes) _, err = io.ReadFull(rand, kbytes)
k = new(big.Int).SetBytes(kbytes) k = new(big.Int).SetBytes(kbytes)
k = k.Mod(k, pub.P) k = k.Mod(k, pub.P)
if k.Sign() != 0 { if k.Sign() != 0 {
break break
} }
} }
if err == nil { if err == nil {
enc = &ElgamalEncryption{ enc = &ElgamalEncryption{
p: pub.P, p: pub.P,
a: new(big.Int).Exp(pub.G, k, pub.P), a: new(big.Int).Exp(pub.G, k, pub.P),
b1: new(big.Int).Exp(pub.Y, k, pub.P), b1: new(big.Int).Exp(pub.Y, k, pub.P),
} }
} }
return return
} }
type ElgPublicKey [256]byte type ElgPublicKey [256]byte
type ElgPrivateKey [256]byte type ElgPrivateKey [256]byte
func (elg ElgPublicKey) Len() int { func (elg ElgPublicKey) Len() int {
return len(elg) return len(elg)
} }
func (elg ElgPublicKey) NewEncrypter() (enc Encrypter, err error) { func (elg ElgPublicKey) NewEncrypter() (enc Encrypter, err error) {
k := createElgamalPublicKey(elg[:]) k := createElgamalPublicKey(elg[:])
enc, err = createElgamalEncryption(k, rand.Reader) enc, err = createElgamalEncryption(k, rand.Reader)
return return
} }
func (elg ElgPrivateKey) Len() int { func (elg ElgPrivateKey) Len() int {
return len(elg) return len(elg)
} }
func (elg ElgPrivateKey) NewDecrypter() (dec Decrypter, err error) { func (elg ElgPrivateKey) NewDecrypter() (dec Decrypter, err error) {
dec = &elgDecrypter{ dec = &elgDecrypter{
k: createElgamalPrivateKey(elg[:]), k: createElgamalPrivateKey(elg[:]),
} }
return return
} }

View File

@ -1,50 +1,49 @@
package crypto package crypto
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"golang.org/x/crypto/openpgp/elgamal" "golang.org/x/crypto/openpgp/elgamal"
"io" "io"
"testing" "testing"
) )
func TestElg(t *testing.T) { func TestElg(t *testing.T) {
k := new(elgamal.PrivateKey) k := new(elgamal.PrivateKey)
err := ElgamalGenerate(k, rand.Reader) err := ElgamalGenerate(k, rand.Reader)
if err == nil { if err == nil {
msg := make([]byte, 222) msg := make([]byte, 222)
_, err := io.ReadFull(rand.Reader, msg) _, err := io.ReadFull(rand.Reader, msg)
if err == nil { if err == nil {
pub := createElgamalPublicKey(k.Y.Bytes()) pub := createElgamalPublicKey(k.Y.Bytes())
enc, err := createElgamalEncryption(pub, rand.Reader) enc, err := createElgamalEncryption(pub, rand.Reader)
if err == nil { if err == nil {
emsg, err := enc.Encrypt(msg) emsg, err := enc.Encrypt(msg)
if err == nil { if err == nil {
dec, err := elgamalDecrypt(k, emsg, true) dec, err := elgamalDecrypt(k, emsg, true)
if err == nil { if err == nil {
if ! bytes.Equal(dec, msg) { if !bytes.Equal(dec, msg) {
t.Logf("%q != %q", dec, msg) t.Logf("%q != %q", dec, msg)
t.Fail() t.Fail()
} }
} else { } else {
t.Logf("decrypt failed: %s", err.Error()) t.Logf("decrypt failed: %s", err.Error())
t.Fail() t.Fail()
} }
} else { } else {
t.Logf("failed to encrypt message: %s", err.Error()) t.Logf("failed to encrypt message: %s", err.Error())
t.Fail() t.Fail()
} }
} else { } else {
t.Logf("failed to create encryption: %s", err.Error()) t.Logf("failed to create encryption: %s", err.Error())
t.Fail() t.Fail()
} }
} else { } else {
t.Logf("failed to generate random message: %s", err.Error()) t.Logf("failed to generate random message: %s", err.Error())
t.Fail() t.Fail()
} }
} else { } else {
t.Logf("error while generating key: %s", err.Error()) t.Logf("error while generating key: %s", err.Error())
t.Fail() t.Fail()
} }
} }

View File

@ -2,16 +2,16 @@ package crypto
// encrypts data // encrypts data
type Encrypter interface { type Encrypter interface {
// encrypt a block of data // encrypt a block of data
// return encrypted block or nil and error if an error happened // return encrypted block or nil and error if an error happened
Encrypt(data []byte) (enc []byte, err error) Encrypt(data []byte) (enc []byte, err error)
} }
type PublicEncryptionKey interface { type PublicEncryptionKey interface {
// create a new encrypter to encrypt data to this public key // create a new encrypter to encrypt data to this public key
NewEncrypter() (Encrypter, error) NewEncrypter() (Encrypter, error)
// length of this public key in bytes // length of this public key in bytes
Len() int Len() int
} }

View File

@ -1,7 +1,7 @@
package crypto package crypto
import ( import (
"crypto/sha256" "crypto/sha256"
) )
var SHA256 = sha256.Sum256 var SHA256 = sha256.Sum256

View File

@ -1,7 +1,7 @@
package crypto package crypto
import ( import (
"crypto/md5" "crypto/md5"
) )
const IPAD = byte(0x36) const IPAD = byte(0x36)
@ -11,33 +11,33 @@ type HMACKey [32]byte
type HMACDigest [16]byte type HMACDigest [16]byte
func (hk HMACKey) xor(p byte) (i []byte) { func (hk HMACKey) xor(p byte) (i []byte) {
i = make([]byte, 64) i = make([]byte, 64)
for idx, b := range hk { for idx, b := range hk {
i[idx] = b ^ p i[idx] = b ^ p
} }
c := 32 c := 32
for c > 0 { for c > 0 {
c-- c--
i[c+32] = p i[c+32] = p
} }
return return
} }
// //
// do i2p hmac // do i2p hmac
// //
func I2PHMAC(data []byte, k HMACKey) (d HMACDigest) { func I2PHMAC(data []byte, k HMACKey) (d HMACDigest) {
buff := make([]byte, 64+len(data))
ip := k.xor(IPAD)
copy(buff, ip)
copy(buff[64:], data)
h := md5.Sum(buff)
buff = make([]byte, 96) buff := make([]byte, 64+len(data))
copy(buff, k.xor(OPAD)) ip := k.xor(IPAD)
copy(buff[64:], h[:]) copy(buff, ip)
// go zeros slices so we do not have to zero copy(buff[64:], data)
d = md5.Sum(buff) h := md5.Sum(buff)
return
buff = make([]byte, 96)
copy(buff, k.xor(OPAD))
copy(buff[64:], h[:])
// go zeros slices so we do not have to zero
d = md5.Sum(buff)
return
} }

View File

@ -1,28 +1,27 @@
package crypto package crypto
import ( import (
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"testing" "testing"
) )
// XXX: IMPLEMENT THIS // XXX: IMPLEMENT THIS
func Test_I2PHMAC(t *testing.T) { func Test_I2PHMAC(t *testing.T) {
data := make([]byte, 64) data := make([]byte, 64)
for idx, _ := range data { for idx, _ := range data {
data[idx] = 1 data[idx] = 1
} }
var k HMACKey var k HMACKey
for idx, _ := range k[:] { for idx, _ := range k[:] {
k[idx] = 1 k[idx] = 1
} }
d := I2PHMAC(data, k) d := I2PHMAC(data, k)
expected_str := "WypV9tIaH1Kn9i7/9OqP6Q==" expected_str := "WypV9tIaH1Kn9i7/9OqP6Q=="
expected, _ := base64.StdEncoding.DecodeString(expected_str) expected, _ := base64.StdEncoding.DecodeString(expected_str)
if ! bytes.Equal(d[:], expected) { if !bytes.Equal(d[:], expected) {
t.Logf("%d vs %d", len(d), len(expected)) t.Logf("%d vs %d", len(d), len(expected))
t.Logf("%q != %q", d, expected) t.Logf("%q != %q", d, expected)
t.Fail() t.Fail()
} }
} }

View File

@ -1,6 +1,5 @@
package crypto package crypto
type RSA2048PublicKey [256]byte type RSA2048PublicKey [256]byte
type RSA2048PrivateKey [512]byte type RSA2048PrivateKey [512]byte
@ -9,4 +8,3 @@ type RSA3072PrivateKey [786]byte
type RSA4096PublicKey [512]byte type RSA4096PublicKey [512]byte
type RSA4096PrivateKey [1024]byte type RSA4096PrivateKey [1024]byte

View File

@ -1,7 +1,7 @@
package crypto package crypto
import ( import (
"errors" "errors"
) )
var ErrBadSignatureSize = errors.New("bad signature size") var ErrBadSignatureSize = errors.New("bad signature size")
@ -10,40 +10,38 @@ var ErrInvalidSignature = errors.New("invalid signature")
// type for verifying signatures // type for verifying signatures
type Verifier interface { type Verifier interface {
// verify hashed data with this signing key // verify hashed data with this signing key
// return nil on valid signature otherwise error // return nil on valid signature otherwise error
VerifyHash(data, sig []byte) error VerifyHash(data, sig []byte) error
// verify an unhashed piece of data by hashing it and calling VerifyHash // verify an unhashed piece of data by hashing it and calling VerifyHash
Verify(data, sig []byte) error Verify(data, sig []byte) error
} }
// key for verifying data // key for verifying data
type SigningPublicKey interface { type SigningPublicKey interface {
// create new Verifier to verify the validity of signatures // create new Verifier to verify the validity of signatures
// return verifier or nil and error if key format is invalid // return verifier or nil and error if key format is invalid
NewVerifier() (Verifier, error) NewVerifier() (Verifier, error)
// get the size of this public key // get the size of this public key
Len() int Len() int
} }
// type for signing data // type for signing data
type Signer interface { type Signer interface {
// sign data with our private key by calling SignHash after hashing the data we are given // sign data with our private key by calling SignHash after hashing the data we are given
// return signature or nil signature and error if an error happened // return signature or nil signature and error if an error happened
Sign(data []byte) (sig []byte, err error) Sign(data []byte) (sig []byte, err error)
// sign hash of data with our private key
// return signature or nil signature and error if an error happened
SignHash(h []byte) (sig []byte, err error)
}
// sign hash of data with our private key
// return signature or nil signature and error if an error happened
SignHash(h []byte) (sig []byte, err error)
}
// key for signing data // key for signing data
type SigningPrivateKey interface { type SigningPrivateKey interface {
// create a new signer to sign data // create a new signer to sign data
// return signer or nil and error if key format is invalid // return signer or nil and error if key format is invalid
NewSigner() (Signer, error) NewSigner() (Signer, error)
Len() int Len() int
} }

View File

@ -1,49 +1,51 @@
package crypto package crypto
import ( import (
"crypto/aes" "crypto/aes"
"crypto/cipher" "crypto/cipher"
) )
type TunnelData [1024]byte type TunnelData [1024]byte
// A symetric key for encrypting tunnel messages // A symetric key for encrypting tunnel messages
type TunnelKey [32]byte type TunnelKey [32]byte
// The initialization vector for a tunnel message // The initialization vector for a tunnel message
type TunnelIV []byte type TunnelIV []byte
type Tunnel struct { type Tunnel struct {
layerKey cipher.Block layerKey cipher.Block
ivKey cipher.Block ivKey cipher.Block
} }
func NewTunnelCrypto(layerKey, ivKey TunnelKey) (t *Tunnel, err error) { func NewTunnelCrypto(layerKey, ivKey TunnelKey) (t *Tunnel, err error) {
t = new(Tunnel) t = new(Tunnel)
t.layerKey, err = aes.NewCipher(layerKey[:]) t.layerKey, err = aes.NewCipher(layerKey[:])
if err == nil { if err == nil {
t.ivKey, err = aes.NewCipher(ivKey[:]) t.ivKey, err = aes.NewCipher(ivKey[:])
} }
if err != nil { if err != nil {
// error happened we don't need t // error happened we don't need t
t = nil t = nil
} }
return return
} }
// encrypt tunnel data in place // encrypt tunnel data in place
func (t *Tunnel) Encrypt(td *TunnelData) { func (t *Tunnel) Encrypt(td *TunnelData) {
data := *td data := *td
t.ivKey.Encrypt(data[16:1024], data[16:1024]) t.ivKey.Encrypt(data[16:1024], data[16:1024])
layerBlock := cipher.NewCBCEncrypter(t.layerKey, data[:16]) layerBlock := cipher.NewCBCEncrypter(t.layerKey, data[:16])
layerBlock.CryptBlocks(data[16:1024], data[16:1024]) layerBlock.CryptBlocks(data[16:1024], data[16:1024])
t.ivKey.Encrypt(data[16:1024], data[16:1024]) t.ivKey.Encrypt(data[16:1024], data[16:1024])
} }
func (t *Tunnel) Decrypt(td *TunnelData) { func (t *Tunnel) Decrypt(td *TunnelData) {
data := *td data := *td
t.ivKey.Decrypt(data[16:1024], data[16:1024]) t.ivKey.Decrypt(data[16:1024], data[16:1024])
layerBlock := cipher.NewCBCDecrypter(t.layerKey, data[:16]) layerBlock := cipher.NewCBCDecrypter(t.layerKey, data[:16])
layerBlock.CryptBlocks(data[16:1024], data[16:1024]) layerBlock.CryptBlocks(data[16:1024], data[16:1024])
t.ivKey.Decrypt(data[16:1024], data[16:1024]) t.ivKey.Decrypt(data[16:1024], data[16:1024])
} }

View File

@ -1,2 +1 @@
package stdi2p package stdi2p

View File

@ -1,14 +1,13 @@
package netdb package netdb
type Reseed interface { type Reseed interface {
// do reseed, return nil on success otherwise error // do reseed, return nil on success otherwise error
// sends down all Netdb entries down chan // sends down all Netdb entries down chan
// closes channel when done // closes channel when done
Reseed(chnl chan *Entry) error Reseed(chnl chan *Entry) error
} }
func GetRandomReseed() Reseed { func GetRandomReseed() Reseed {
// TODO: hardcoded value // TODO: hardcoded value
return HTTPSReseed("https://i2p.rocks:445/") return HTTPSReseed("https://i2p.rocks:445/")
} }

View File

@ -1,18 +1,18 @@
package netdb package netdb
import ( import (
"io" "io"
"path/filepath" "path/filepath"
) )
type Entry struct { type Entry struct {
fname string fname string
} }
func (e *Entry) FilePath(n StdNetDB) (str string) { func (e *Entry) FilePath(n StdNetDB) (str string) {
return filepath.Join(string(n), e.fname) return filepath.Join(string(n), e.fname)
} }
func (e *Entry) WriteTo(w io.Writer) (err error) { func (e *Entry) WriteTo(w io.Writer) (err error) {
return return
} }

View File

@ -3,6 +3,6 @@ package netdb
type HTTPSReseed string type HTTPSReseed string
func (r HTTPSReseed) Reseed(chnl chan *Entry) (err error) { func (r HTTPSReseed) Reseed(chnl chan *Entry) (err error) {
close(chnl) close(chnl)
return return
} }

View File

@ -1,94 +1,92 @@
package netdb package netdb
import ( import (
log "github.com/golang/glog" "github.com/bounce-chat/go-i2p/lib/common"
"github.com/bounce-chat/go-i2p/lib/common" log "github.com/golang/glog"
"io" "io"
"os" "os"
) )
// standard network database implementation // standard network database implementation
type StdNetDB string type StdNetDB string
// get netdb path // get netdb path
func (db StdNetDB) Path() string { func (db StdNetDB) Path() string {
return string(db) return string(db)
} }
// //
// return how many routers we know about in our network database // return how many routers we know about in our network database
// //
func (db StdNetDB) KnownPeerCount() (routers int) { func (db StdNetDB) KnownPeerCount() (routers int) {
return return
} }
// return true if the network db directory exists and is writable // return true if the network db directory exists and is writable
func (db StdNetDB) Exists() bool { func (db StdNetDB) Exists() bool {
return common.FileExists(db.Path()) return common.FileExists(db.Path())
} }
func (db StdNetDB) SaveEntry(e *Entry) (err error) { func (db StdNetDB) SaveEntry(e *Entry) (err error) {
var f io.WriteCloser var f io.WriteCloser
f, err = os.OpenFile(e.FilePath(db), os.O_WRONLY, 0600) f, err = os.OpenFile(e.FilePath(db), os.O_WRONLY, 0600)
if err == nil { if err == nil {
err = e.WriteTo(f) err = e.WriteTo(f)
if err != nil { if err != nil {
log.Errorf("failed to write netdb entry: %s", err.Error()) log.Errorf("failed to write netdb entry: %s", err.Error())
} }
f.Close() f.Close()
} else { } else {
log.Errorf("failed to save netdb entry: %s", err.Error()) log.Errorf("failed to save netdb entry: %s", err.Error())
} }
return return
} }
// reseed if we have less than minRouters known routers // reseed if we have less than minRouters known routers
// returns error if reseed failed // returns error if reseed failed
func (db StdNetDB) Reseed(minRouters int) (err error) { func (db StdNetDB) Reseed(minRouters int) (err error) {
current := db.KnownPeerCount() current := db.KnownPeerCount()
if current <= minRouters { if current <= minRouters {
// we need to reseed // we need to reseed
rs := GetRandomReseed() rs := GetRandomReseed()
log.Infof("Reseeding from %s", rs) log.Infof("Reseeding from %s", rs)
chnl := make(chan *Entry) chnl := make(chan *Entry)
// receive entries from reseed // receive entries from reseed
go func(c chan *Entry) { go func(c chan *Entry) {
count := 0 count := 0
for { for {
e, ok := <- c e, ok := <-c
if ok { if ok {
// got an entry // got an entry
// save it to our netdb // save it to our netdb
err := db.SaveEntry(e) err := db.SaveEntry(e)
if err == nil { if err == nil {
count ++ count++
} }
} }
} }
}(chnl) // call }(chnl) // call
err = rs.Reseed(chnl) err = rs.Reseed(chnl)
} }
return return
} }
// ensure that the network database exists and is seeded with a minimum number of routers // ensure that the network database exists and is seeded with a minimum number of routers
func (db StdNetDB) Ensure(minRouters int) (err error) { func (db StdNetDB) Ensure(minRouters int) (err error) {
if ! db.Exists() { if !db.Exists() {
err = db.Create() err = db.Create()
} }
if err == nil { if err == nil {
// database directory ensured // database directory ensured
// try to reseed // try to reseed
err = db.Reseed(minRouters) err = db.Reseed(minRouters)
} }
return return
} }
// create base network database directory // create base network database directory
func (db StdNetDB) Create() (err error) { func (db StdNetDB) Create() (err error) {
log.Infof("Create network database in %s", db.Path()) log.Infof("Create network database in %s", db.Path())
err = os.Mkdir(db.Path(), 0600) err = os.Mkdir(db.Path(), 0600)
return return
} }

View File

@ -1,31 +1,30 @@
package router package router
import ( import (
"github.com/bounce-chat/go-i2p/lib/config" "github.com/bounce-chat/go-i2p/lib/config"
"github.com/bounce-chat/go-i2p/lib/netdb" "github.com/bounce-chat/go-i2p/lib/netdb"
) )
// i2p router type // i2p router type
type Router struct { type Router struct {
cfg *config.RouterConfig cfg *config.RouterConfig
ndb netdb.StdNetDB ndb netdb.StdNetDB
} }
func CreateRouter() (r *Router, err error) { func CreateRouter() (r *Router, err error) {
cfg := config.Router cfg := config.Router
r = &Router{ r = &Router{
cfg: cfg, cfg: cfg,
ndb: netdb.StdNetDB(cfg.NetDbDir), ndb: netdb.StdNetDB(cfg.NetDbDir),
} }
return return
} }
// run i2p router mainloop // run i2p router mainloop
func (r *Router) Run() { func (r *Router) Run() {
// make sure the netdb is ready // make sure the netdb is ready
err := r.ndb.Ensure(r.cfg.Bootstrap.LowPeerThreshold) err := r.ndb.Ensure(r.cfg.Bootstrap.LowPeerThreshold)
if err == nil { if err == nil {
// netdb ready // netdb ready
} }
} }

View File

@ -4,4 +4,3 @@ i2p ssu transport implementation
*/ */
package ssu package ssu

View File

@ -1,3 +1 @@
package ssu package ssu

View File

@ -1,7 +1,5 @@
package stdi2p package stdi2p
// Router Identity // Router Identity
type RouterIdentity struct { type RouterIdentity struct {
} }

View File

@ -1,6 +1,4 @@
package stdi2p package stdi2p
type RouterInfo struct { type RouterInfo struct {
} }

View File

@ -1,92 +1,92 @@
package stdi2p package stdi2p
import ( import (
"encoding/binary" "encoding/binary"
"github.com/bounce-chat/go-i2p/lib/crypto" "github.com/bounce-chat/go-i2p/lib/crypto"
) )
const ( const (
CERT_NULL = iota CERT_NULL = iota
CERT_HASHCASH CERT_HASHCASH
CERT_HIDDEN CERT_HIDDEN
CERT_SIGNED CERT_SIGNED
CERT_MULTIPLE CERT_MULTIPLE
CERT_KEY CERT_KEY
) )
const ( const (
KEYCERT_SIGN_DSA_SHA1 = iota KEYCERT_SIGN_DSA_SHA1 = iota
KEYCERT_SIGN_P256 KEYCERT_SIGN_P256
KEYCERT_SIGN_P384 KEYCERT_SIGN_P384
KEYCERT_SIGN_P521 KEYCERT_SIGN_P521
KEYCERT_SIGN_RSA2048 KEYCERT_SIGN_RSA2048
KEYCERT_SIGN_RSA3072 KEYCERT_SIGN_RSA3072
KEYCERT_SIGN_RSA4096 KEYCERT_SIGN_RSA4096
KEYCERT_SIGN_ED25519 KEYCERT_SIGN_ED25519
) )
const ( const (
KEYCERT_CRYPTO_ELG = iota KEYCERT_CRYPTO_ELG = iota
) )
// used to append data to existing data structures // used to append data to existing data structures
type Certificate []byte type Certificate []byte
// return the type of this certificate // return the type of this certificate
func (c Certificate) Type() byte { func (c Certificate) Type() byte {
return c[0] return c[0]
} }
// get the length of the data in this certificate // get the length of the data in this certificate
func (c Certificate) Len() int { func (c Certificate) Len() int {
return int(binary.BigEndian.Uint16(c[1:3])) return int(binary.BigEndian.Uint16(c[1:3]))
} }
// get the data for this certificate or null if non exists // get the data for this certificate or null if non exists
func (c Certificate) Data() (d []byte) { func (c Certificate) Data() (d []byte) {
l := c.Len() l := c.Len()
if l > 0 { if l > 0 {
// TODO(psi): check bounds correctly? // TODO(psi): check bounds correctly?
d = c[3:3+l] d = c[3 : 3+l]
} }
return return
} }
// a Certificate of type KEY // a Certificate of type KEY
type KeyCert []byte type KeyCert []byte
func (c KeyCert) Type() byte { func (c KeyCert) Type() byte {
return Certificate(c).Type() return Certificate(c).Type()
} }
func (c KeyCert) Data() []byte { func (c KeyCert) Data() []byte {
return Certificate(c).Data() return Certificate(c).Data()
} }
// get the signing public key from this key cert // get the signing public key from this key cert
func (c KeyCert) SigningPublicKey() (k crypto.SigningPublicKey) { func (c KeyCert) SigningPublicKey() (k crypto.SigningPublicKey) {
data := c.Data() data := c.Data()
ktype := binary.BigEndian.Uint16(data[:2]) ktype := binary.BigEndian.Uint16(data[:2])
// set data to be the key data now // set data to be the key data now
data = data[4:] data = data[4:]
// determine the key type // determine the key type
if ktype == KEYCERT_SIGN_DSA_SHA1 { if ktype == KEYCERT_SIGN_DSA_SHA1 {
var pk crypto.DSAPublicKey var pk crypto.DSAPublicKey
copy(pk[:], data[:pk.Len()]) copy(pk[:], data[:pk.Len()])
k = pk k = pk
} else if ktype == KEYCERT_SIGN_P256 { } else if ktype == KEYCERT_SIGN_P256 {
var pk crypto.ECP256PublicKey var pk crypto.ECP256PublicKey
copy(pk[:], data[:pk.Len()]) copy(pk[:], data[:pk.Len()])
k = pk k = pk
} else if ktype == KEYCERT_SIGN_P384 { } else if ktype == KEYCERT_SIGN_P384 {
var pk crypto.ECP384PublicKey var pk crypto.ECP384PublicKey
copy(pk[:], data[:pk.Len()]) copy(pk[:], data[:pk.Len()])
k = pk k = pk
} else if ktype == KEYCERT_SIGN_P521 { } else if ktype == KEYCERT_SIGN_P521 {
var pk crypto.ECP521PublicKey var pk crypto.ECP521PublicKey
copy(pk[:], data[:pk.Len()]) copy(pk[:], data[:pk.Len()])
k = pk k = pk
} }
// TODO: rsa/eddsa // TODO: rsa/eddsa
return return
} }

View File

@ -1,6 +1,5 @@
package stdi2p package stdi2p
// i2p date time stamp // i2p date time stamp
type Date [8]byte type Date [8]byte

View File

@ -1,10 +1,10 @@
package stdi2p package stdi2p
import( import (
"github.com/bounce-chat/go-i2p/lib/common/base32" "github.com/bounce-chat/go-i2p/lib/common/base32"
"github.com/bounce-chat/go-i2p/lib/common/base64" "github.com/bounce-chat/go-i2p/lib/common/base64"
"github.com/bounce-chat/go-i2p/lib/crypto" "github.com/bounce-chat/go-i2p/lib/crypto"
"strings" "strings"
) )
// a network endpoint inside i2p // a network endpoint inside i2p
@ -13,47 +13,47 @@ type Destination []byte
// obtain public elgamal key // obtain public elgamal key
func (dest Destination) PublicKey() (k crypto.PublicEncryptionKey) { func (dest Destination) PublicKey() (k crypto.PublicEncryptionKey) {
cert := dest.Certificate() cert := dest.Certificate()
if cert.Type() == CERT_KEY { if cert.Type() == CERT_KEY {
// TODO(psi): check for key cert and included encryption key // TODO(psi): check for key cert and included encryption key
} else { } else {
var ek crypto.ElgPublicKey var ek crypto.ElgPublicKey
copy(ek[:], dest[:256]) copy(ek[:], dest[:256])
k = ek k = ek
} }
return return
} }
// obtain destination certificate // obtain destination certificate
func (dest Destination) Certificate() Certificate { func (dest Destination) Certificate() Certificate {
return Certificate(dest[128+256:]) return Certificate(dest[128+256:])
} }
// gets this destination's signing key // gets this destination's signing key
// if there is a keycert in this destination the signing key in there is used // if there is a keycert in this destination the signing key in there is used
func (dest Destination) SigningPublicKey() (k crypto.SigningPublicKey) { func (dest Destination) SigningPublicKey() (k crypto.SigningPublicKey) {
cert := dest.Certificate() cert := dest.Certificate()
if cert.Type() == CERT_KEY { if cert.Type() == CERT_KEY {
// we have a key certificate // we have a key certificate
// extract the signing key from the key cert // extract the signing key from the key cert
k = KeyCert(cert).SigningPublicKey() k = KeyCert(cert).SigningPublicKey()
} else { } else {
var pk crypto.DSAPublicKey var pk crypto.DSAPublicKey
copy(pk[:], dest[256:256+128]) copy(pk[:], dest[256:256+128])
k = pk k = pk
} }
return return
} }
// return the .b32.i2p address // return the .b32.i2p address
func (dest Destination) Base32Address() (str string) { func (dest Destination) Base32Address() (str string) {
h := crypto.SHA256(dest) h := crypto.SHA256(dest)
str = strings.Trim(base32.EncodeToString(h[:]), "=") str = strings.Trim(base32.EncodeToString(h[:]), "=")
str += ".b32.i2p" str += ".b32.i2p"
return return
} }
func (dest Destination) Base64() (str string) { func (dest Destination) Base64() (str string) {
str = base64.EncodeToString(dest) str = base64.EncodeToString(dest)
return return
} }

View File

@ -1,7 +1,5 @@
package stdi2p package stdi2p
// an su3 archive // an su3 archive
type SU3 struct { type SU3 struct {
} }

View File

@ -1,104 +1,102 @@
package tunnel package tunnel
import( import (
"encoding/binary" "encoding/binary"
) )
const ( const (
DT_LOCAL = iota DT_LOCAL = iota
DT_TUNNEL DT_TUNNEL
DT_ROUTER DT_ROUTER
DT_UNUSED DT_UNUSED
) )
type DelayFactor byte type DelayFactor byte
type DeliveryInstructions []byte type DeliveryInstructions []byte
func (di DeliveryInstructions) DeliveryType() byte { func (di DeliveryInstructions) DeliveryType() byte {
return (di[0] & 0x30) >> 4 return (di[0] & 0x30) >> 4
} }
func (di DeliveryInstructions) IsFragmented() bool { func (di DeliveryInstructions) IsFragmented() bool {
return (di[0] & 0x08) == 0x08 return (di[0] & 0x08) == 0x08
} }
// get the tunnel id in this devilevery instrcutions or 0 if not applicable // get the tunnel id in this devilevery instrcutions or 0 if not applicable
func (di DeliveryInstructions) TunnelID() (tid uint32) { func (di DeliveryInstructions) TunnelID() (tid uint32) {
if di.DeliveryType() == DT_TUNNEL { if di.DeliveryType() == DT_TUNNEL {
// TODO(psi): what if this is 0? // TODO(psi): what if this is 0?
tid = binary.BigEndian.Uint32(di[1:5]) tid = binary.BigEndian.Uint32(di[1:5])
} }
return return
} }
// do we have a delay factor? // do we have a delay factor?
func (di DeliveryInstructions) HasDelay() bool { func (di DeliveryInstructions) HasDelay() bool {
return (di[0] & 0x10) == 0x10 return (di[0] & 0x10) == 0x10
} }
// get the delay factor if it exists // get the delay factor if it exists
func (di DeliveryInstructions) Delay() (d DelayFactor) { func (di DeliveryInstructions) Delay() (d DelayFactor) {
if di.HasDelay() { if di.HasDelay() {
t := di.DeliveryType() t := di.DeliveryType()
if t == DT_TUNNEL { if t == DT_TUNNEL {
d = DelayFactor(di[37]) d = DelayFactor(di[37])
} else if t == DT_ROUTER { } else if t == DT_ROUTER {
d = DelayFactor(di[36]) d = DelayFactor(di[36])
} }
} }
return return
} }
func (di DeliveryInstructions) HasExtendedOptions() bool { func (di DeliveryInstructions) HasExtendedOptions() bool {
return (di[0] & 0x04) == 0x04 return (di[0] & 0x04) == 0x04
} }
// get the to hash for these delivery instructions or nil if not applicable // get the to hash for these delivery instructions or nil if not applicable
func (di DeliveryInstructions) ToHash() (h []byte) { func (di DeliveryInstructions) ToHash() (h []byte) {
t := di.DeliveryType() t := di.DeliveryType()
if t == DT_TUNNEL { if t == DT_TUNNEL {
h = di[5:37] h = di[5:37]
} else if t == DT_ROUTER || t == DT_LOCAL { } else if t == DT_ROUTER || t == DT_LOCAL {
h = di[4:36] h = di[4:36]
} }
return return
} }
// get the i2np message id or 0 if not applicable // get the i2np message id or 0 if not applicable
func (di DeliveryInstructions) MessageID() (msgid uint32) { func (di DeliveryInstructions) MessageID() (msgid uint32) {
if di.IsFragmented() { if di.IsFragmented() {
idx := 1 idx := 1
t := di.DeliveryType() t := di.DeliveryType()
if t == DT_TUNNEL { if t == DT_TUNNEL {
idx += 36 idx += 36
} else if t == DT_ROUTER { } else if t == DT_ROUTER {
idx += 32 idx += 32
} }
if di.HasDelay() { if di.HasDelay() {
idx ++ idx++
} }
msgid = binary.BigEndian.Uint32(di[idx:]) msgid = binary.BigEndian.Uint32(di[idx:])
} }
return return
} }
// get the size of the associated i2np fragment // get the size of the associated i2np fragment
func (di DeliveryInstructions) GetFragmentSize() uint16 { func (di DeliveryInstructions) GetFragmentSize() uint16 {
idx := 5 idx := 5
t := di.DeliveryType() t := di.DeliveryType()
if t == DT_TUNNEL { if t == DT_TUNNEL {
idx += 36 idx += 36
} else if t == DT_ROUTER { } else if t == DT_ROUTER {
idx += 32 idx += 32
} }
if di.HasDelay() { if di.HasDelay() {
idx ++ idx++
} }
if di.HasExtendedOptions() { if di.HasExtendedOptions() {
// add extended options length to idx // add extended options length to idx
} }
return binary.BigEndian.Uint16(di[idx:]) return binary.BigEndian.Uint16(di[idx:])
} }

View File

@ -1,8 +1,8 @@
package tunnel package tunnel
import ( import (
"github.com/bounce-chat/go-i2p/lib/crypto" "encoding/binary"
"encoding/binary" "github.com/bounce-chat/go-i2p/lib/crypto"
) )
type TunnelID uint32 type TunnelID uint32
@ -11,10 +11,10 @@ type TunnelID uint32
type TunnelMessage crypto.TunnelData type TunnelMessage crypto.TunnelData
func (tm TunnelMessage) ID() (tid TunnelID) { func (tm TunnelMessage) ID() (tid TunnelID) {
tid = TunnelID(binary.BigEndian.Uint32(tm[:4])) tid = TunnelID(binary.BigEndian.Uint32(tm[:4]))
return return
} }
func (tm TunnelMessage) IV() crypto.TunnelIV { func (tm TunnelMessage) IV() crypto.TunnelIV {
return tm[4:20] return tm[4:20]
} }

View File

@ -1,10 +1,9 @@
package tunnel package tunnel
import ( import (
"github.com/bounce-chat/go-i2p/lib/crypto" "github.com/bounce-chat/go-i2p/lib/crypto"
) )
type Participant struct { type Participant struct {
decryption *crypto.Tunnel decryption *crypto.Tunnel
} }

29
main.go
View File

@ -1,26 +1,23 @@
package main package main
import ( import (
"github.com/bounce-chat/go-i2p/lib/router"
"github.com/bounce-chat/go-i2p/lib/router" "flag"
log "github.com/golang/glog"
log "github.com/golang/glog"
"flag"
) )
func main() { func main() {
flag.Parse() flag.Parse()
log.Info("parsing i2p router configuration") log.Info("parsing i2p router configuration")
log.Info("starting up i2p router") log.Info("starting up i2p router")
r, err := router.CreateRouter() r, err := router.CreateRouter()
if err == nil { if err == nil {
r.Run() r.Run()
} else { } else {
log.Errorf("failed to create i2p router: %s", err) log.Errorf("failed to create i2p router: %s", err)
} }
} }