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
import (
b32 "encoding/base32"
b32 "encoding/base32"
)
// i2p base32 encoding
var I2PEncoding *b32.Encoding = b32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567")
// wrapper arround encoding for encoding to string
func EncodeToString(data []byte) (str string) {
str = I2PEncoding.EncodeToString(data)
return
str = I2PEncoding.EncodeToString(data)
return
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,14 +2,14 @@ package crypto
// decrypts data
type Decrypter interface {
// decrypt a block of data
// return decrypted block or nil and error if error happens
Decrypt(data []byte) ([]byte, error)
// decrypt a block of data
// return decrypted block or nil and error if error happens
Decrypt(data []byte) ([]byte, error)
}
type PrivateEncryptionKey interface {
// 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
NewDecrypter() (Decrypter, error)
// 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
NewDecrypter() (Decrypter, error)
}

View File

@ -1,152 +1,150 @@
package crypto
import (
"crypto/dsa"
"crypto/sha1"
"crypto/rand"
"io"
"math/big"
"crypto/dsa"
"crypto/rand"
"crypto/sha1"
"io"
"math/big"
)
var dsap = new(big.Int).SetBytes([]byte{
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,
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,
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,
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,
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,
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,
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,
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,
})
var dsaq = new(big.Int).SetBytes([]byte{
0xa5, 0xdf, 0xc2, 0x8f, 0xef, 0x4c, 0xa1, 0xe2, 0x86, 0x74, 0x4c, 0xd8, 0xee, 0xd9, 0xd2, 0x9d,
0x68, 0x40, 0x46, 0xb7,
});
0xa5, 0xdf, 0xc2, 0x8f, 0xef, 0x4c, 0xa1, 0xe2, 0x86, 0x74, 0x4c, 0xd8, 0xee, 0xd9, 0xd2, 0x9d,
0x68, 0x40, 0x46, 0xb7,
})
var dsag = new(big.Int).SetBytes([]byte{
0x0c, 0x1f, 0x4d, 0x27, 0xd4, 0x00, 0x93, 0xb4, 0x29, 0xe9, 0x62, 0xd7, 0x22, 0x38, 0x24, 0xe0,
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85, 0xe4, 0x3d, 0x13, 0x6c, 0xdc, 0xfc,
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,
0xb3, 0xdb, 0xb1, 0x4a, 0x90, 0x5e, 0x7b, 0x2b, 0x3e, 0x93, 0xbe, 0x47, 0x08, 0xcb, 0xcc, 0x82,
})
var param = dsa.Parameters{
P: dsap,
Q: dsaq,
G: dsag,
P: dsap,
Q: dsaq,
G: dsag,
}
// generate a dsa keypair
func DSAGenerate(priv *dsa.PrivateKey, rand io.Reader) error {
// put our paramters in
priv.P = param.P
priv.Q = param.Q
priv.G = param.G
// generate the keypair
return dsa.GenerateKey(priv, rand)
// put our paramters in
priv.P = param.P
priv.Q = param.Q
priv.G = param.G
// generate the keypair
return dsa.GenerateKey(priv, rand)
}
// create i2p dsa public key given its public component
func createDSAPublicKey(Y *big.Int) *dsa.PublicKey {
return &dsa.PublicKey{
Parameters: param,
Y: Y,
}
return &dsa.PublicKey{
Parameters: param,
Y: Y,
}
}
// createa i2p dsa private key given its public component
func createDSAPrivkey(X *big.Int) *dsa.PrivateKey {
Y := new(big.Int)
Y.Exp(dsag, X, dsap)
return &dsa.PrivateKey{
PublicKey: dsa.PublicKey{
Parameters: param,
Y: Y,
},
X: X,
}
Y := new(big.Int)
Y.Exp(dsag, X, dsap)
return &dsa.PrivateKey{
PublicKey: dsa.PublicKey{
Parameters: param,
Y: Y,
},
X: X,
}
}
type DSAVerifier struct {
k *dsa.PublicKey
k *dsa.PublicKey
}
type DSAPublicKey [128]byte
// create a new dsa verifier
func (k DSAPublicKey) NewVerifier() (v Verifier, err error) {
v = &DSAVerifier{
k: createDSAPublicKey(new(big.Int).SetBytes(k[:])),
}
return
v = &DSAVerifier{
k: createDSAPublicKey(new(big.Int).SetBytes(k[:])),
}
return
}
// verify data with a dsa public key
func (v *DSAVerifier) Verify(data, sig []byte) (err error) {
h := sha1.Sum(data)
err = v.VerifyHash(h[:], sig)
return
h := sha1.Sum(data)
err = v.VerifyHash(h[:], sig)
return
}
// verify hash of data with a dsa public key
func (v *DSAVerifier) VerifyHash(h, sig []byte) (err error) {
if len(sig) == 40 {
r := new(big.Int).SetBytes(sig[:20])
s := new(big.Int).SetBytes(sig[20:])
if dsa.Verify(v.k, h, r, s) {
// valid signature
} else {
// invalid signature
err = ErrInvalidSignature
}
} else {
err = ErrBadSignatureSize
}
return
if len(sig) == 40 {
r := new(big.Int).SetBytes(sig[:20])
s := new(big.Int).SetBytes(sig[20:])
if dsa.Verify(v.k, h, r, s) {
// valid signature
} else {
// invalid signature
err = ErrInvalidSignature
}
} else {
err = ErrBadSignatureSize
}
return
}
func (k DSAPublicKey) Len() int {
return len(k)
return len(k)
}
type DSASigner struct {
k *dsa.PrivateKey
k *dsa.PrivateKey
}
type DSAPrivateKey [20]byte
// create a new dsa signer
func (k DSAPrivateKey) NewSigner() (s Signer, err error) {
s = &DSASigner{
k: createDSAPrivkey(new (big.Int).SetBytes(k[:])),
}
return
s = &DSASigner{
k: createDSAPrivkey(new(big.Int).SetBytes(k[:])),
}
return
}
func (ds *DSASigner) Sign(data []byte) (sig []byte, err error) {
h := sha1.Sum(data)
sig, err = ds.SignHash(h[:])
return
h := sha1.Sum(data)
sig, err = ds.SignHash(h[:])
return
}
func (ds *DSASigner) SignHash(h []byte) (sig []byte, err error) {
var r, s *big.Int
r, s, err = dsa.Sign(rand.Reader, ds.k, h)
if err == nil {
sig = make([]byte, 40)
copy(sig, r.Bytes())
copy(sig[20:], s.Bytes())
}
return
var r, s *big.Int
r, s, err = dsa.Sign(rand.Reader, ds.k, h)
if err == nil {
sig = make([]byte, 40)
copy(sig, r.Bytes())
copy(sig[20:], s.Bytes())
}
return
}
func (k DSAPrivateKey) Len() int {
return len(k)
return len(k)
}

View File

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

View File

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

View File

@ -1,32 +1,32 @@
package crypto
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"errors"
"golang.org/x/crypto/openpgp/elgamal"
"io"
"math/big"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"errors"
"golang.org/x/crypto/openpgp/elgamal"
"io"
"math/big"
)
var elgp = new(big.Int).SetBytes([]byte{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0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3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
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,
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,
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,
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,
})
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
func ElgamalGenerate(priv *elgamal.PrivateKey, rand io.Reader) (err error) {
priv.P = elgp
priv.G = elgg
xBytes := make([]byte, priv.P.BitLen()/8)
_, err = io.ReadFull(rand, xBytes)
if err == nil {
// set private key
priv.X = new(big.Int).SetBytes(xBytes)
// compute public key
priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P)
}
return
priv.P = elgp
priv.G = elgg
xBytes := make([]byte, priv.P.BitLen()/8)
_, err = io.ReadFull(rand, xBytes)
if err == nil {
// set private key
priv.X = new(big.Int).SetBytes(xBytes)
// compute public key
priv.Y = new(big.Int).Exp(priv.G, priv.X, priv.P)
}
return
}
type elgDecrypter struct {
k *elgamal.PrivateKey
k *elgamal.PrivateKey
}
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?
return
dec, err = elgamalDecrypt(elg.k, data, true) // TODO(psi): should this be true or false?
return
}
// decrypt an elgamal encrypted message, i2p style
func elgamalDecrypt(priv *elgamal.PrivateKey, data []byte, zeroPadding bool) (decrypted []byte, err error) {
a := new(big.Int)
b := new(big.Int)
idx := 0
if zeroPadding {
idx ++
}
a.SetBytes(data[idx : idx + 256])
if zeroPadding {
idx ++
}
b.SetBytes(data[idx + 256:])
a := new(big.Int)
b := new(big.Int)
idx := 0
if zeroPadding {
idx++
}
a.SetBytes(data[idx : idx+256])
if zeroPadding {
idx++
}
b.SetBytes(data[idx+256:])
// 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()
// 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()
// check digest
d := sha256.Sum256(m[33:255])
good := 0
if subtle.ConstantTimeCompare(d[:], m[1:33]) == 1 {
// decryption successful
good = 1
} else {
// decrypt failed
err = ElgDecryptFail
}
// copy result
decrypted = make([]byte, 222)
subtle.ConstantTimeCopy(good, decrypted, m[33:255])
// check digest
d := sha256.Sum256(m[33:255])
good := 0
if subtle.ConstantTimeCompare(d[:], m[1:33]) == 1 {
// decryption successful
good = 1
} else {
// decrypt failed
err = ElgDecryptFail
}
// copy result
decrypted = make([]byte, 222)
subtle.ConstantTimeCopy(good, decrypted, m[33:255])
if good == 0 {
// if decrypt failed nil out decrypted slice
decrypted = nil
}
return
if good == 0 {
// if decrypt failed nil out decrypted slice
decrypted = nil
}
return
}
type ElgamalEncryption struct {
p, a, b1 *big.Int
p, a, b1 *big.Int
}
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) {
if len(data) > 222 {
err = ElgEncryptTooBig
return
}
mbytes := make([]byte, 255)
mbytes[0] = 0xFF
copy(mbytes[33:], data)
// do sha256 of payload
d := sha256.Sum256(mbytes[33:len(data)+33])
copy(mbytes[1:], d[:])
m := new(big.Int).SetBytes(mbytes)
// do encryption
b := new(big.Int).Mod(new(big.Int).Mul(elg.b1, m), elg.p).Bytes()
if len(data) > 222 {
err = ElgEncryptTooBig
return
}
mbytes := make([]byte, 255)
mbytes[0] = 0xFF
copy(mbytes[33:], data)
// do sha256 of payload
d := sha256.Sum256(mbytes[33 : len(data)+33])
copy(mbytes[1:], d[:])
m := new(big.Int).SetBytes(mbytes)
// do encryption
b := new(big.Int).Mod(new(big.Int).Mul(elg.b1, m), elg.p).Bytes()
if zeroPadding {
encrypted = make([]byte, 514)
copy(encrypted[1:], elg.a.Bytes())
copy(encrypted[258:], b)
} else {
encrypted = make([]byte, 512)
copy(encrypted, elg.a.Bytes())
copy(encrypted[256:], b)
}
return
if zeroPadding {
encrypted = make([]byte, 514)
copy(encrypted[1:], elg.a.Bytes())
copy(encrypted[258:], b)
} else {
encrypted = make([]byte, 512)
copy(encrypted, elg.a.Bytes())
copy(encrypted[256:], b)
}
return
}
// create an elgamal public key from byte slice
func createElgamalPublicKey(data []byte) (k *elgamal.PublicKey) {
if len(data) == 256 {
k = &elgamal.PublicKey{
G: elgg,
P: elgp,
Y: new(big.Int).SetBytes(data),
}
}
return
if len(data) == 256 {
k = &elgamal.PublicKey{
G: elgg,
P: elgp,
Y: new(big.Int).SetBytes(data),
}
}
return
}
// create an elgamal private key from byte slice
func createElgamalPrivateKey(data []byte) (k *elgamal.PrivateKey) {
if len(data) == 256 {
x := new(big.Int).SetBytes(data)
y := new(big.Int).Exp(elgg, x, elgp)
k = &elgamal.PrivateKey{
PublicKey: elgamal.PublicKey{
Y: y,
G: elgg,
P: elgp,
},
X: x,
}
}
return
if len(data) == 256 {
x := new(big.Int).SetBytes(data)
y := new(big.Int).Exp(elgg, x, elgp)
k = &elgamal.PrivateKey{
PublicKey: elgamal.PublicKey{
Y: y,
G: elgg,
P: elgp,
},
X: x,
}
}
return
}
// create a new elgamal encryption session
func createElgamalEncryption(pub *elgamal.PublicKey, rand io.Reader) (enc *ElgamalEncryption, err error) {
kbytes := make([]byte, 256)
k := new(big.Int)
for err == nil {
_, err = io.ReadFull(rand, kbytes)
k = new(big.Int).SetBytes(kbytes)
k = k.Mod(k, pub.P)
if k.Sign() != 0 {
break
}
}
if err == nil {
enc = &ElgamalEncryption{
p: pub.P,
a: new(big.Int).Exp(pub.G, k, pub.P),
b1: new(big.Int).Exp(pub.Y, k, pub.P),
}
}
return
kbytes := make([]byte, 256)
k := new(big.Int)
for err == nil {
_, err = io.ReadFull(rand, kbytes)
k = new(big.Int).SetBytes(kbytes)
k = k.Mod(k, pub.P)
if k.Sign() != 0 {
break
}
}
if err == nil {
enc = &ElgamalEncryption{
p: pub.P,
a: new(big.Int).Exp(pub.G, k, pub.P),
b1: new(big.Int).Exp(pub.Y, k, pub.P),
}
}
return
}
type ElgPublicKey [256]byte
type ElgPrivateKey [256]byte
func (elg ElgPublicKey) Len() int {
return len(elg)
return len(elg)
}
func (elg ElgPublicKey) NewEncrypter() (enc Encrypter, err error) {
k := createElgamalPublicKey(elg[:])
enc, err = createElgamalEncryption(k, rand.Reader)
return
k := createElgamalPublicKey(elg[:])
enc, err = createElgamalEncryption(k, rand.Reader)
return
}
func (elg ElgPrivateKey) Len() int {
return len(elg)
return len(elg)
}
func (elg ElgPrivateKey) NewDecrypter() (dec Decrypter, err error) {
dec = &elgDecrypter{
k: createElgamalPrivateKey(elg[:]),
}
return
dec = &elgDecrypter{
k: createElgamalPrivateKey(elg[:]),
}
return
}

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
package crypto
import (
"crypto/md5"
"crypto/md5"
)
const IPAD = byte(0x36)
@ -11,16 +11,16 @@ type HMACKey [32]byte
type HMACDigest [16]byte
func (hk HMACKey) xor(p byte) (i []byte) {
i = make([]byte, 64)
for idx, b := range hk {
i[idx] = b ^ p
}
c := 32
for c > 0 {
c--
i[c+32] = p
}
return
i = make([]byte, 64)
for idx, b := range hk {
i[idx] = b ^ p
}
c := 32
for c > 0 {
c--
i[c+32] = p
}
return
}
//
@ -28,16 +28,16 @@ func (hk HMACKey) xor(p byte) (i []byte) {
//
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, 64+len(data))
ip := k.xor(IPAD)
copy(buff, ip)
copy(buff[64:], data)
h := md5.Sum(buff)
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
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
import (
"bytes"
"encoding/base64"
"testing"
"bytes"
"encoding/base64"
"testing"
)
// XXX: IMPLEMENT THIS
func Test_I2PHMAC(t *testing.T) {
data := make([]byte, 64)
for idx, _ := range data {
data[idx] = 1
}
var k HMACKey
for idx, _ := range k[:] {
k[idx] = 1
}
d := I2PHMAC(data, k)
expected_str := "WypV9tIaH1Kn9i7/9OqP6Q=="
expected, _ := base64.StdEncoding.DecodeString(expected_str)
if ! bytes.Equal(d[:], expected) {
t.Logf("%d vs %d", len(d), len(expected))
t.Logf("%q != %q", d, expected)
t.Fail()
}
data := make([]byte, 64)
for idx, _ := range data {
data[idx] = 1
}
var k HMACKey
for idx, _ := range k[:] {
k[idx] = 1
}
d := I2PHMAC(data, k)
expected_str := "WypV9tIaH1Kn9i7/9OqP6Q=="
expected, _ := base64.StdEncoding.DecodeString(expected_str)
if !bytes.Equal(d[:], expected) {
t.Logf("%d vs %d", len(d), len(expected))
t.Logf("%q != %q", d, expected)
t.Fail()
}
}

View File

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

View File

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

View File

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

View File

@ -1,2 +1 @@
package stdi2p

View File

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

View File

@ -1,18 +1,18 @@
package netdb
import (
"io"
"path/filepath"
"io"
"path/filepath"
)
type Entry struct {
fname string
fname 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) {
return
return
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1 @@
package ssu

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

27
main.go
View File

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