Skip to content

Commit

Permalink
nonce prepended to payload
Browse files Browse the repository at this point in the history
  • Loading branch information
ivcosla committed May 28, 2019
1 parent b917300 commit 811e95f
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions internal/noise/noise.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ package noise

import (
"crypto/rand"
"encoding/binary"
"fmt"

"github.com/flynn/noise"

"github.com/skycoin/skywire/pkg/cipher"
)

// packetsTillRekey is the number of packages after which we want to rekey for the noise protocol
const packetsTillRekey = 10

// Config hold noise parameters.
type Config struct {
LocalPK cipher.PubKey // Local instance static public key.
Expand All @@ -31,8 +30,9 @@ type Noise struct {
enc *noise.CipherState
dec *noise.CipherState

encN uint32 // counter to inform encrypting CipherState to re-key
decN uint32 // counter to inform decrypting CipherState to re-key
seq uint32 // sequence number, used as nonce for both encrypting and decrypting
//encN uint32 // counter to inform encrypting CipherState to re-key
//decN uint32 // counter to inform decrypting CipherState to re-key
}

// New creates a new Noise with:
Expand Down Expand Up @@ -119,21 +119,22 @@ func (ns *Noise) RemoteStatic() cipher.PubKey {
// EncryptUnsafe encrypts plaintext without interlocking, should only
// be used with external lock.
func (ns *Noise) EncryptUnsafe(plaintext []byte) []byte {
if ns.encN++; ns.encN > packetsTillRekey {
ns.enc.Rekey()
ns.encN = 0
}
return ns.enc.Encrypt(nil, nil, plaintext)
ns.seq++
seq := make([]byte, 4)
binary.BigEndian.PutUint32(seq, ns.seq)
fmt.Println("seq is: ", seq)

return append(seq, ns.enc.Cipher().Encrypt(nil, uint64(ns.seq), nil, plaintext)...)
}

// DecryptUnsafe decrypts ciphertext without interlocking, should only
// be used with external lock.
func (ns *Noise) DecryptUnsafe(ciphertext []byte) ([]byte, error) {
if ns.decN++; ns.decN > packetsTillRekey {
ns.dec.Rekey()
ns.decN = 0
}
return ns.dec.Decrypt(nil, nil, ciphertext)
fmt.Println("decrypt first 4 bytes: ", ciphertext[:4])
fmt.Println("decrypt seq: ", ciphertext)
seq := binary.BigEndian.Uint32(ciphertext[:4])
fmt.Println("decyphered seq is: ", seq)
return ns.dec.Cipher().Decrypt(nil, uint64(seq),nil, ciphertext[4:])
}

// HandshakeFinished indicate whether handshake was completed.
Expand Down

0 comments on commit 811e95f

Please sign in to comment.