예제 #1
0
func (b boxSecretKey) Box(receiver BoxPublicKey, nonce *Nonce, msg []byte) ([]byte, error) {
	var tmp [32]byte
	box.Precompute(&tmp, (*[32]byte)(receiver.ToRawBoxKeyPointer()), (*[32]byte)(&b.key))
	ret := box.Seal([]byte{}, msg, (*[24]byte)(nonce),
		(*[32]byte)(receiver.ToRawBoxKeyPointer()), (*[32]byte)(&b.key))
	return ret, nil
}
예제 #2
0
func TestEncryptDecrypt(t *testing.T) {
	peerPubKey, _, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Errorf("failed key gen %s", err)
		return
	}

	_, ownPrivKey, err := box.GenerateKey(rand.Reader)
	if err != nil {
		t.Errorf("failed key gen %s", err)
		return
	}

	var sharedKey [32]byte
	box.Precompute(&sharedKey, peerPubKey, ownPrivKey)

	msg := []byte("|wtf am i doing|")

	cipher, err := node.Encrypt(msg, &sharedKey)

	if err != nil {
		t.Errorf("failed to encrypt %s", err)
		return
	}

	plain, err := node.Decrypt(cipher, &sharedKey)
	if err != nil {
		t.Errorf("failed to decrypt: %s", err)
		return
	}

	if !bytes.Equal(msg, plain) {
		t.Errorf("expected %s doesn't equal actual %s", string(msg), string(plain))
	}
}
예제 #3
0
func (cah *connectionAwaitHandshake) start() (bool, error) {
	helloSeg, err := cah.makeHello()
	if err != nil {
		return false, err
	}
	buf := new(bytes.Buffer)
	if _, err := helloSeg.WriteTo(buf); err != nil {
		return false, err
	}
	if err := cah.send(buf.Bytes()); err != nil {
		return false, err
	}

	if seg, err := capn.ReadFromStream(cah.socket, nil); err == nil {
		if hello := msgs.ReadRootHello(seg); cah.verifyHello(&hello) {
			sessionKey := [32]byte{}
			remotePublicKey := [32]byte{}
			copy(remotePublicKey[:], hello.PublicKey())
			box.Precompute(&sessionKey, &remotePublicKey, cah.privateKey)
			cah.sessionKey = &sessionKey
			cah.nonceAryOut[0] = 128
			cah.nonce = 0
			cah.nextState()
		} else {
			return false, fmt.Errorf("Received erroneous hello from server")
		}
	} else {
		return false, err
	}

	return false, nil
}
예제 #4
0
func (c *Conn) handshakeAsServer(ctx context.Context) error {
	// Check that a private key has actually been specified.
	c.curves = c.cfg.Curvek
	if keyIsZero(&c.curves) {
		return fmt.Errorf("Server private key not specified.")
	}

	// Derive server public key from server private key.
	if c.cfg.CurveK != nil {
		c.curveS = *c.cfg.CurveK
	} else {
		curve25519.ScalarBaseMult(&c.curveS, &c.curves)
	}

	err := c.hsReadClientHello()
	if err != nil {
		return err
	}

	err = c.hsWriteServerHello()
	if err != nil {
		return err
	}

	// Determine the shared secret key used for encryption.
	box.Precompute(&c.curveCtSt, &c.curveCt, &c.curvest)

	err = c.hsReadClientCommence()
	if err != nil {
		return err
	}

	return nil
}
예제 #5
0
func (c *Conn) hcWriteClientHello() error {
	// Generate a random client nonce.
	_, err := io.ReadFull(c.cfg.Rand, c.nonceC.initial[:])
	if err != nil {
		return err
	}

	// Ensure client nonce does not have last bit set.
	c.nonceC.initial[23] &= 0xFE

	// Generate our transient public and private key.
	Ct, ct, err := box.GenerateKey(c.cfg.Rand)
	if err != nil {
		return err
	}

	c.curveCt = *Ct
	c.curvect = *ct

	// Send client hello
	b := make([]byte, 65, 81)
	b[0] = byte(opClientHello)
	binary.LittleEndian.PutUint32(b[1:5], clientHelloMagic)
	copy(b[9:41], c.curveCt[:])
	copy(b[41:65], c.nonceC.initial[:])

	var nonce [24]byte
	c.nonceC.Next(&nonce)
	box.Precompute(&c.curveCtS, &c.curveS, &c.curvect)
	b = box.SealAfterPrecomputation(b, nil, &nonce, &c.curveCtS)

	return c.conn.WriteFrame(b)
}
예제 #6
0
// NewSecureConn instantiates a new io.ReadWriteCloser backed by a
// SecureReader and SecureWriter with public keys already exchanged.
func NewSecureConn(conn net.Conn) (io.ReadWriteCloser, error) {
	// Generate random key pair
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return nil, ErrKeyGeneration
	}

	// Send public key
	if _, err := conn.Write(pub[:]); err != nil {
		return nil, ErrKeyExchange
	}

	// Read other side's public key
	var otherPub [32]byte
	if _, err := io.ReadFull(conn, otherPub[:]); err != nil {
		return nil, ErrKeyExchange
	}

	var key [32]byte
	box.Precompute(&key, &otherPub, priv)

	return struct {
		io.Reader
		io.Writer
		io.Closer
	}{
		Reader: &SecureReader{r: conn, key: &key},
		Writer: &SecureWriter{w: conn, key: &key},
		Closer: conn,
	}, nil
}
예제 #7
0
// NewSecureReader instantiates a new SecureReader using given keys
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	sr := SecureReader{
		reader: r,
	}
	box.Precompute(&sr.sharedKey, pub, priv)
	return sr
}
예제 #8
0
// NewSecureWriter instantiates a new SecureWriter.
func NewSecureWriter(w io.Writer, priv, pub *[keySize]byte) io.Writer {
	s := &secureWriter{
		writer: w,
	}
	box.Precompute(&s.sharedKey, pub, priv)
	return s
}
예제 #9
0
// NewSecureReader instantiates a new SecureReader.
func NewSecureReader(r io.Reader, priv, pub *[keySize]byte) io.Reader {
	s := &secureReader{
		reader: r,
	}
	box.Precompute(&s.sharedKey, pub, priv)
	return s
}
예제 #10
0
func MakeSharedKey(sharedKey, peersPublicKey, privateKey *[32]byte) *[32]byte {
	if sharedKey == nil {
		sharedKey = new([32]byte)
	}
	box.Precompute(sharedKey, peersPublicKey, privateKey)
	return sharedKey
}
예제 #11
0
// NewSecureReader creates a new SecureReader.
func NewSecureReader(r io.Reader, privateKey, peerPublicKey *[32]byte) *SecureReader {
	sr := &SecureReader{
		reader: r,
	}
	box.Precompute(&sr.sharedKey, peerPublicKey, privateKey)
	return sr
}
예제 #12
0
// NewSecureWriter creates a new SecureWriter which wraps the provided writer.
func NewSecureWriter(w io.Writer, privateKey, peerPublicKey *[32]byte) *SecureWriter {
	sw := &SecureWriter{
		writer: w,
	}
	box.Precompute(&sw.sharedKey, peerPublicKey, privateKey)
	return sw
}
예제 #13
0
func newConn(sock *net.UDPConn, peerIdentity, publicKey, privateKey []byte, domain string) *conn {
	if len(peerIdentity) != 32 || len(publicKey) != 32 || len(privateKey) != 32 {
		panic("wrong key size")
	}
	c := &conn{
		domain: domain,

		packetIn: make(chan packet),
		sock:     sock,

		readRequest:  make(chan []byte),
		writeRequest: make(chan []byte),
		ioResult:     make(chan opResult),

		toSend:   list.New(),
		sendFree: list.New(),

		received: ringbuf.New(recvBufferSize),
	}
	// Key setup.
	copy(c.peerIdentity[:], peerIdentity)
	var pub, priv [32]byte
	copy(pub[:], publicKey)
	copy(priv[:], privateKey)
	box.Precompute(&c.sharedKey, &pub, &priv)

	// Send blocks
	for i := 0; i < numSendBlocks; i++ {
		c.sendFree.PushBack(new(block))
	}

	go c.pump()
	return c
}
예제 #14
0
// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[32]byte) io.Writer {
	sw := &SecureWriter{
		wr:  w,
		key: &[32]byte{},
	}
	box.Precompute(sw.key, pub, priv)
	return sw
}
예제 #15
0
// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, privateKey, peersPublicKey *[32]byte) io.Reader {
	ret := &SecureReader{
		r: r,
	}
	ret.unreadBuf = ret.buf[:0]
	box.Precompute(&ret.sharedKey, peersPublicKey, privateKey)
	return ret
}
예제 #16
0
// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[KeyLength]byte) io.Writer {
	sharedKey := new([KeyLength]byte)
	box.Precompute(sharedKey, pub, priv)
	return SecureWriter{
		w,
		sharedKey,
	}
}
예제 #17
0
// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	sr := &SecureReader{
		rd:  r,
		key: &[32]byte{},
	}
	box.Precompute(sr.key, pub, priv)
	return sr
}
예제 #18
0
// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[32]byte) io.Writer {
	sw := SecureWriter{
		w:         w,
		sharedKey: &[32]byte{},
	}
	box.Precompute(sw.sharedKey, pub, priv)
	return sw
}
예제 #19
0
// NewSecureReader instantiates a new SecureReader
func NewSecureReader(r io.Reader, priv, pub *[KeyLength]byte) io.Reader {
	sharedKey := new([KeyLength]byte)
	box.Precompute(sharedKey, pub, priv)
	return SecureReader{
		r,
		sharedKey,
	}
}
예제 #20
0
func (n naclBoxSecretKey) Precompute(
	sender saltpack.BoxPublicKey) saltpack.BoxPrecomputedSharedKey {
	var res naclBoxPrecomputedSharedKey
	box.Precompute((*[32]byte)(&res),
		(*[32]byte)(sender.ToRawBoxKeyPointer()),
		(*[32]byte)(n.Private))
	return res
}
예제 #21
0
// FormSessionKey is used during encrypted protocol introduction.
func formSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte) *[32]byte {
	var sharedKey [32]byte
	box.Precompute(&sharedKey, remotePublicKey, localPrivateKey)
	sharedKeySlice := sharedKey[:]
	sharedKeySlice = append(sharedKeySlice, secretKey...)
	sessionKey := sha256.Sum256(sharedKeySlice)
	return &sessionKey
}
예제 #22
0
파일: crypto.go 프로젝트: 40a/ejson
// NewEncrypter instantiates an Encrypter after pre-computing the shared key for
// the owned keypair and the given decrypter public key.
func NewEncrypter(kp *Keypair, peerPublic [32]byte) *Encrypter {
	var shared [32]byte
	box.Precompute(&shared, &peerPublic, &kp.Private)
	return &Encrypter{
		Keypair:    kp,
		PeerPublic: peerPublic,
		SharedKey:  shared,
	}
}
예제 #23
0
// NewWriter instantiates a new Writer.
func NewWriter(w io.Writer, priv, pub *[32]byte) *Writer {
	sw := &Writer{
		writer: w,
	}

	box.Precompute(&sw.sharedKey, pub, priv)

	return sw
}
예제 #24
0
// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[32]byte) io.Writer {
	sharedKey := new([32]byte)
	box.Precompute(sharedKey, pub, priv)

	return SecureReadWriteCloser{
		writer: w,
		secret: sharedKey,
	}
}
예제 #25
0
// NewSecureReader returns a secureReader initialied with the given parameters.
func NewSecureReader(r io.Reader, priv, pub *[32]byte) io.Reader {
	s := &secureReader{
		underlying: r,
		packet:     &dataPacket{},
		buffer:     make([]byte, bufferSize),
	}
	nacl.Precompute(&s.sharedKey, pub, priv)
	return s
}
예제 #26
0
func newSecureReader(r io.Reader, priv, peersPub *[32]byte) *naclReader {
	n := &naclReader{
		sharedKey: &[keyLen]byte{},
		in:        r,
	}

	box.Precompute(n.sharedKey, peersPub, priv)
	return n
}
예제 #27
0
// handleConnection is the server side function
// handles the public keys exchange as handshake and message serving
func handleConnection(conn net.Conn) error {
	defer conn.Close()
	// Handshake
	// Generate server side keys
	pub, pri, err := box.GenerateKey(rand.Reader)
	if *pri == *pub || err != nil {
		return err
	}

	// cpubk is the client public key
	cpubk := make([]byte, 2048)
	n, err := conn.Read(cpubk)
	if err != nil {
		return err
	}
	// client public key
	cpub := &[32]byte{}
	copy(cpub[:], cpubk[:n])

	// send server public key to client
	_, err = conn.Write(pub[:])
	if err != nil {
		return err
	}

	shared := &[32]byte{}
	// Let's get a bit faster
	box.Precompute(shared, cpub, pri)

	// reading message
	msg := make([]byte, 2048)
	n, err = conn.Read(msg)
	if err != nil {
		fmt.Errorf("could not read message %s", err)
		return err
	}
	// Generate a nonc, to keep it simple we synchronize
	// nonces between Clietn and Server
	nonc := &helper.Nonce{}
	nv := nonc.GenerateNonce(*shared)

	out := make([]byte, n)
	// decrypt message
	dm, ok := box.OpenAfterPrecomputation(out, msg[:n], &nv, shared)
	if !ok {
		m := fmt.Sprintf("could not decrypt message %v", msg[:n])
		return errors.New(m)
	}

	// Send back message encrypted
	em := box.SealAfterPrecomputation(nil, dm[n:], &nv, shared)
	_, err = conn.Write(em)
	if err != nil {
		return err
	}
	return nil
}
예제 #28
0
// NewSecureWriter creates a new SecureWriter that writes to w.
func NewSecureWriter(w io.Writer, priv, pub *[ksize]byte) io.Writer {
	sw := &SecureWriter{
		w:   w,
		key: [ksize]byte{},
		buf: make([]byte, maxBoxSize),
	}
	box.Precompute(&sw.key, pub, priv)
	return sw
}
예제 #29
0
// NewSecureWriter instantiates a new SecureWriter
func NewSecureWriter(w io.Writer, priv, pub *[keySize]byte) io.Writer {
	var sw secureWriter

	sw.w = w
	// pre-size the buffer to the max sealed message size
	sw.buffer = make([]byte, 0, box.Overhead+maxMessageSize)
	box.Precompute(&sw.sharedKey, pub, priv)
	return &sw
}
예제 #30
0
// NewSecureReader returns an initialized SecureReader structure.
func NewSecureReader(r io.Reader, priv, pub *[KeySize]byte) io.Reader {
	var s = SecureReader{
		r:   r,
		buf: make([]byte, MaxMessageSize),
	}
	// Precompute a shared key for speeding up operations
	box.Precompute(&s.sharedPrecomputedKey, pub, priv)
	return &s
}