├── .gitignore ├── LICENSE ├── README.md ├── address.go ├── crypto.go ├── curve_sign.go ├── curve_sign_test.go ├── key.go ├── key_test.go ├── memory_store.go ├── session.go └── store.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | The MIT License 3 | 4 | Copyright (c) 2010-2018 Google, Inc. http://angularjs.org 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libsignal-protocol-go 2 | 3 | #### A GoLang library for communicating using the Signal . 4 | 5 | This library currently implements the "X3DH" (or "Extended Triple Diffie-Hellman") key agreement protocol. X3DH establishes a shared secret key between two parties who mutually authenticate each other based on public keys. X3DH provides forward secrecy and cryptographic deniability. Work is currently on to implement the Double Ratchet Algorithm that provides perfect forward secrecy. 6 | 7 | 1. [https://signal.org/docs/specifications/x3dh](https://signal.org/docs/specifications/x3dh) 8 | 2. [https://signal.org/docs/specifications/doubleratchet/](https://signal.org/docs/specifications/doubleratchet/) 9 | 10 | 11 | ##### Try the end-to-end sending and receiving signal protocol flow 12 | 13 | ```console 14 | go test -v -timeout 30s github.com/dosco/signal-go -run ^TestFlow$ 15 | ``` 16 | -------------------------------------------------------------------------------- /address.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | type Address struct { 4 | name string 5 | deviceID uint32 6 | } 7 | 8 | func NewAddress(name string, deviceID uint32) *Address { 9 | return &Address{ 10 | name: name, 11 | deviceID: deviceID, 12 | } 13 | } 14 | 15 | func (a *Address) Name() string { 16 | return a.name 17 | } 18 | 19 | func (a *Address) DeviceID() uint32 { 20 | return a.deviceID 21 | } 22 | -------------------------------------------------------------------------------- /crypto.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | "crypto/rand" 7 | "fmt" 8 | "io" 9 | ) 10 | 11 | const ( 12 | KeySize = 32 13 | NonceSize = 24 14 | ) 15 | 16 | // GenerateNonce creates a new random nonce. 17 | func GenerateNonce() (*[NonceSize]byte, error) { 18 | nonce := new([NonceSize]byte) 19 | _, err := io.ReadFull(rand.Reader, nonce[:]) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | return nonce, nil 25 | } 26 | 27 | func EncryptAEAD(key, message, ad []byte) ([]byte, error) { 28 | c, err := aes.NewCipher(key) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | gcm, err := cipher.NewGCMWithNonceSize(c, NonceSize) 34 | if err != nil { 35 | return nil, err 36 | } 37 | 38 | nonce, err := GenerateNonce() 39 | if err != nil { 40 | return nil, err 41 | } 42 | 43 | buf := gcm.Seal(nil, nonce[:], message, ad) 44 | return append(nonce[:], buf...), nil 45 | } 46 | 47 | func DecryptAEAD(key, message, ad []byte) ([]byte, error) { 48 | if len(message) <= NonceSize { 49 | return nil, fmt.Errorf("len(message) <= NonceSize") 50 | } 51 | 52 | c, err := aes.NewCipher(key) 53 | if err != nil { 54 | return nil, err 55 | } 56 | 57 | gcm, err := cipher.NewGCMWithNonceSize(c, NonceSize) 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | out, err := gcm.Open(nil, message[:NonceSize], message[NonceSize:], ad) 63 | if err != nil { 64 | return nil, err 65 | } 66 | return out, nil 67 | } 68 | -------------------------------------------------------------------------------- /curve_sign.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import ( 4 | "crypto/sha512" 5 | 6 | "github.com/agl/ed25519" 7 | "github.com/agl/ed25519/edwards25519" 8 | ) 9 | 10 | // Curve implementation GPLv3 taken from 11 | // https://github.com/janimo/textsecure/tree/master/curve25519sign 12 | 13 | func Sign(privateKey *[32]byte, message []byte, random [64]byte) *[64]byte { 14 | 15 | // Calculate Ed25519 public key from Curve25519 private key 16 | var A edwards25519.ExtendedGroupElement 17 | var publicKey [32]byte 18 | edwards25519.GeScalarMultBase(&A, privateKey) 19 | A.ToBytes(&publicKey) 20 | 21 | // Calculate r 22 | diversifier := [32]byte{ 23 | 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 24 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 25 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 26 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} 27 | 28 | var r [64]byte 29 | h := sha512.New() 30 | h.Write(diversifier[:]) 31 | h.Write(privateKey[:]) 32 | h.Write(message) 33 | h.Write(random[:]) 34 | h.Sum(r[:0]) 35 | 36 | // Calculate R 37 | var rReduced [32]byte 38 | edwards25519.ScReduce(&rReduced, &r) 39 | var R edwards25519.ExtendedGroupElement 40 | edwards25519.GeScalarMultBase(&R, &rReduced) 41 | 42 | var encodedR [32]byte 43 | R.ToBytes(&encodedR) 44 | 45 | // Calculate S = r + SHA2-512(R || A_ed || msg) * a (mod L) 46 | var hramDigest [64]byte 47 | h.Reset() 48 | h.Write(encodedR[:]) 49 | h.Write(publicKey[:]) 50 | h.Write(message) 51 | h.Sum(hramDigest[:0]) 52 | var hramDigestReduced [32]byte 53 | edwards25519.ScReduce(&hramDigestReduced, &hramDigest) 54 | 55 | var s [32]byte 56 | edwards25519.ScMulAdd(&s, &hramDigestReduced, privateKey, &rReduced) 57 | 58 | signature := new([64]byte) 59 | copy(signature[:], encodedR[:]) 60 | copy(signature[32:], s[:]) 61 | signature[63] |= publicKey[31] & 0x80 62 | 63 | return signature 64 | } 65 | 66 | // Verify checks whether the message has a valid signature. 67 | func Verify(publicKey [32]byte, message []byte, signature *[64]byte) bool { 68 | 69 | publicKey[31] &= 0x7F 70 | 71 | /* Convert the Curve25519 public key into an Ed25519 public key. In 72 | particular, convert Curve25519's "montgomery" x-coordinate into an 73 | Ed25519 "edwards" y-coordinate: 74 | ed_y = (mont_x - 1) / (mont_x + 1) 75 | NOTE: mont_x=-1 is converted to ed_y=0 since fe_invert is mod-exp 76 | Then move the sign bit into the pubkey from the signature. 77 | */ 78 | 79 | var edY, one, montX, montXMinusOne, montXPlusOne edwards25519.FieldElement 80 | edwards25519.FeFromBytes(&montX, &publicKey) 81 | edwards25519.FeOne(&one) 82 | edwards25519.FeSub(&montXMinusOne, &montX, &one) 83 | edwards25519.FeAdd(&montXPlusOne, &montX, &one) 84 | edwards25519.FeInvert(&montXPlusOne, &montXPlusOne) 85 | edwards25519.FeMul(&edY, &montXMinusOne, &montXPlusOne) 86 | 87 | var A_ed [32]byte 88 | edwards25519.FeToBytes(&A_ed, &edY) 89 | 90 | A_ed[31] |= signature[63] & 0x80 91 | signature[63] &= 0x7F 92 | 93 | return ed25519.Verify(&A_ed, message, signature) 94 | } 95 | -------------------------------------------------------------------------------- /curve_sign_test.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import ( 4 | "crypto/rand" 5 | "io" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "golang.org/x/crypto/curve25519" 10 | ) 11 | 12 | // Curve implementation GPLv3 taken from 13 | // https://github.com/janimo/textsecure/tree/master/curve25519sign 14 | 15 | func randBytes(data []byte) { 16 | if _, err := io.ReadFull(rand.Reader, data); err != nil { 17 | panic(err) 18 | } 19 | } 20 | 21 | func TestSign(t *testing.T) { 22 | msg := make([]byte, 200) 23 | 24 | var priv, pub [32]byte 25 | var random [64]byte 26 | 27 | // Test for random values of the keys, nonce and message 28 | for i := 0; i < 100; i++ { 29 | randBytes(priv[:]) 30 | priv[0] &= 248 31 | priv[31] &= 63 32 | priv[31] |= 64 33 | curve25519.ScalarBaseMult(&pub, &priv) 34 | randBytes(random[:]) 35 | randBytes(msg) 36 | sig := Sign(&priv, msg, random) 37 | v := Verify(pub, msg, sig) 38 | assert.True(t, v, "Verify must work") 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /key.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import ( 4 | "crypto/rand" 5 | "io" 6 | "math/big" 7 | 8 | "golang.org/x/crypto/curve25519" 9 | ) 10 | 11 | type PrivKey struct { 12 | Key [32]byte 13 | } 14 | 15 | type PubKey struct { 16 | Key [32]byte 17 | } 18 | 19 | type KeyPair struct { 20 | Priv *PrivKey 21 | Pub *PubKey 22 | } 23 | 24 | type PreKey struct { 25 | KeyID int64 26 | *KeyPair 27 | } 28 | 29 | type SignedPreKey struct { 30 | KeyID int64 31 | Signature *[64]byte 32 | *KeyPair 33 | } 34 | 35 | func GenerateKeyPair() *KeyPair { 36 | var priv PrivKey 37 | if _, err := io.ReadFull(rand.Reader, priv.Key[:]); err != nil { 38 | panic(err) 39 | } 40 | 41 | priv.Key[0] &= 248 42 | priv.Key[31] &= 63 43 | priv.Key[31] |= 64 44 | 45 | var pub PubKey 46 | curve25519.ScalarBaseMult(&pub.Key, &priv.Key) 47 | 48 | return &KeyPair{Priv: &priv, Pub: &pub} 49 | } 50 | 51 | func GenerateRegistrationId() uint64 { 52 | nBig, err := rand.Int(rand.Reader, big.NewInt(9223372036854775807)) 53 | if err != nil { 54 | panic(err) 55 | } 56 | return nBig.Uint64() 57 | } 58 | 59 | func GenerateIdentityKeyPair() *KeyPair { 60 | return GenerateKeyPair() 61 | } 62 | 63 | func GenerateEphemeralKeyPair() *KeyPair { 64 | return GenerateKeyPair() 65 | } 66 | 67 | func GeneratePreKey(keyID int64) *PreKey { 68 | return &PreKey{keyID, GenerateKeyPair()} 69 | } 70 | 71 | func GenerateSignedPreKey(identityKeyPair *KeyPair, keyID int64) *SignedPreKey { 72 | kp := GenerateKeyPair() 73 | 74 | var random [64]byte 75 | if _, err := io.ReadFull(rand.Reader, random[:]); err != nil { 76 | panic(err) 77 | } 78 | 79 | sig := Sign(&identityKeyPair.Priv.Key, kp.Pub.Key[:], random) 80 | return &SignedPreKey{ 81 | KeyID: keyID, 82 | KeyPair: kp, 83 | Signature: sig, 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /key_test.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import "testing" 4 | 5 | func TestFlow(t *testing.T) { 6 | msA := NewMemoryStore() 7 | msB := NewMemoryStore() 8 | 9 | // Alice 10 | idA := GenerateRegistrationId() 11 | msA.PutLocalRegistrationID(idA) 12 | 13 | ikpA := GenerateIdentityKeyPair() 14 | msA.PutIdentityKeyPair(ikpA) 15 | 16 | pkA := GeneratePreKey(1) 17 | msA.PutPreKey(1, pkA) 18 | 19 | spkA := GenerateSignedPreKey(ikpA, 1) 20 | msA.PutSignedPreKey(1, spkA) 21 | 22 | // Bob 23 | 24 | idB := GenerateRegistrationId() 25 | msB.PutLocalRegistrationID(idB) 26 | 27 | ikpB := GenerateIdentityKeyPair() 28 | msB.PutIdentityKeyPair(ikpB) 29 | 30 | pkB := GeneratePreKey(1) 31 | msB.PutPreKey(1, pkB) 32 | 33 | spkB := GenerateSignedPreKey(ikpB, 1) 34 | msB.PutSignedPreKey(1, spkB) 35 | 36 | bobPreKeys := BobPreKeyBundle{ 37 | Recipient: NewAddress("+141566112222", 1), 38 | RegistrationId: idB, 39 | DeviceID: 1, 40 | 41 | IdentityKeyPub: ikpB.Pub, 42 | 43 | SignedPreKeyID: 1, 44 | SignedPreKeyPub: spkB.Pub, 45 | SignedPreKeySignature: spkB.Signature, 46 | 47 | OneTimePreKeyID: 1, 48 | OneTimePreKeyPub: pkB.Pub, 49 | } 50 | 51 | ss, err := NewSenderSession(msA, &bobPreKeys) 52 | if err != nil { 53 | t.Fatal(err) 54 | } 55 | 56 | aliceMsg, err := ss.sendFirstMessage([]byte("Hello World!!!")) 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | 61 | rs, err := NewReceiverSession(msB, aliceMsg) 62 | if err != nil { 63 | t.Fatal(err) 64 | } 65 | 66 | plaintext, err := rs.processFirstMessage() 67 | if err != nil { 68 | t.Fatal(err) 69 | } 70 | 71 | if plaintext != "Hello World!!!" { 72 | t.Errorf("Message failed to decrypt") 73 | } 74 | 75 | t.Logf("Decryption successful: %s", plaintext) 76 | 77 | } 78 | -------------------------------------------------------------------------------- /memory_store.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import "fmt" 4 | 5 | type MemoryStore struct { 6 | localRegistrationID uint64 7 | identityKeyPair *KeyPair 8 | identityKeys map[uint32]*[32]byte 9 | preKeys map[uint32]*PreKey 10 | signedPreKeys map[uint32]*SignedPreKey 11 | } 12 | 13 | var ( 14 | NotFound error = fmt.Errorf("not found") 15 | ) 16 | 17 | func NewMemoryStore() *MemoryStore { 18 | return &MemoryStore{ 19 | identityKeys: make(map[uint32]*[32]byte), 20 | preKeys: make(map[uint32]*PreKey), 21 | signedPreKeys: make(map[uint32]*SignedPreKey), 22 | } 23 | } 24 | 25 | func (s *MemoryStore) GetLocalRegistrationID() (uint64, error) { 26 | return s.localRegistrationID, nil 27 | } 28 | 29 | func (s *MemoryStore) PutLocalRegistrationID(id uint64) error { 30 | s.localRegistrationID = id 31 | return nil 32 | } 33 | 34 | func (s *MemoryStore) GetIdentityKeyPair() (*KeyPair, error) { 35 | return s.identityKeyPair, nil 36 | } 37 | 38 | func (s *MemoryStore) PutIdentityKeyPair(keyPair *KeyPair) error { 39 | s.identityKeyPair = keyPair 40 | return nil 41 | } 42 | 43 | func (s *MemoryStore) GetIdentityKey(keyID uint32) (*[32]byte, error) { 44 | v, ok := s.identityKeys[keyID] 45 | if ok { 46 | return v, nil 47 | } 48 | return nil, NotFound 49 | } 50 | 51 | func (s *MemoryStore) PutIdentityKey(keyID uint32, identityKey *[32]byte) error { 52 | s.identityKeys[keyID] = identityKey 53 | return nil 54 | } 55 | 56 | func (s *MemoryStore) GetPreKey(keyID uint32) (*PreKey, error) { 57 | v, ok := s.preKeys[keyID] 58 | if ok { 59 | return v, nil 60 | } 61 | return nil, NotFound 62 | } 63 | 64 | func (s *MemoryStore) PutPreKey(keyID uint32, preKey *PreKey) error { 65 | s.preKeys[keyID] = preKey 66 | return nil 67 | } 68 | 69 | func (s *MemoryStore) GetSignedPreKey(keyID uint32) (*SignedPreKey, error) { 70 | v, ok := s.signedPreKeys[keyID] 71 | if ok { 72 | return v, nil 73 | } 74 | return nil, NotFound 75 | } 76 | 77 | func (s *MemoryStore) PutSignedPreKey(keyID uint32, signedPreKey *SignedPreKey) error { 78 | s.signedPreKeys[keyID] = signedPreKey 79 | return nil 80 | } 81 | -------------------------------------------------------------------------------- /session.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "fmt" 7 | "io" 8 | 9 | "golang.org/x/crypto/curve25519" 10 | "golang.org/x/crypto/hkdf" 11 | ) 12 | 13 | var diversifier = [32]byte{ 14 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 15 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 16 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 17 | 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} 18 | 19 | type derivedKeys struct { 20 | rootKey [32]byte 21 | chainKey [32]byte 22 | index uint32 23 | } 24 | 25 | type messageKeys struct { 26 | CipherKey []byte 27 | MacKey []byte 28 | Iv []byte 29 | Index uint32 30 | } 31 | 32 | func (dk *derivedKeys) getMessageKeys() (*messageKeys, error) { 33 | m := hmac.New(sha256.New, dk.chainKey[:]) 34 | m.Write([]byte{1}) 35 | b := m.Sum(nil) 36 | 37 | okm := HKDF(b, nil, []byte("WhisperMessageKeys"), 80) 38 | return &messageKeys{ 39 | CipherKey: okm[:32], 40 | MacKey: okm[32:64], 41 | Iv: okm[64:], 42 | Index: dk.index, 43 | }, nil 44 | } 45 | 46 | func (dk *derivedKeys) nextChainKey() [32]byte { 47 | m := hmac.New(sha256.New, dk.chainKey[:]) 48 | m.Write([]byte{2}) 49 | b := m.Sum(nil) 50 | 51 | dk.index += 1 52 | copy(dk.chainKey[:], b) 53 | return dk.chainKey 54 | } 55 | 56 | func DH(priv *PrivKey, pub *PubKey) *[32]byte { 57 | var sharedKey [32]byte 58 | curve25519.ScalarMult(&sharedKey, &priv.Key, &pub.Key) 59 | return &sharedKey 60 | } 61 | 62 | func KDF(dh ...[]byte) *derivedKeys { 63 | fkm := make([]byte, 0, 32*5) 64 | fkm = append(fkm, diversifier[:]...) 65 | 66 | for i := range dh { 67 | fkm = append(fkm, dh[i]...) 68 | } 69 | b := HKDF(fkm, nil, []byte("WhisperText"), 64) 70 | dk := &derivedKeys{index: 0} 71 | copy(dk.rootKey[:], b[:32]) 72 | copy(dk.chainKey[:], b[32:]) 73 | 74 | return dk 75 | } 76 | 77 | func HKDF(km, salt, info []byte, size int) []byte { 78 | hkdf := hkdf.New(sha256.New, km, salt, info) 79 | 80 | secrets := make([]byte, size) 81 | n, err := io.ReadFull(hkdf, secrets) 82 | if err != nil { 83 | panic(err) 84 | } 85 | if n != size { 86 | panic(fmt.Errorf("error n != size")) 87 | } 88 | return secrets 89 | } 90 | 91 | type BobPreKeyBundle struct { 92 | Recipient *Address 93 | RegistrationId uint64 94 | DeviceID uint32 95 | 96 | IdentityKeyPub *PubKey 97 | 98 | SignedPreKeyID uint32 99 | SignedPreKeyPub *PubKey 100 | SignedPreKeySignature *[64]byte 101 | 102 | OneTimePreKeyID int32 103 | OneTimePreKeyPub *PubKey 104 | } 105 | 106 | type SenderSession struct { 107 | store Store 108 | 109 | sk *derivedKeys 110 | ad []byte 111 | 112 | identityKeyPub *PubKey 113 | ephemeralKeyPub *PubKey 114 | 115 | signedPreKeyID uint32 116 | oneTimePreKeyID int32 117 | } 118 | 119 | func NewSenderSession(store Store, b *BobPreKeyBundle) (*SenderSession, error) { 120 | s := &SenderSession{store: store} 121 | 122 | //if !b.identityStore.IsTrustedIdentity(b.recipientID, theirIdentityKey) { 123 | // return 0, NotTrustedError{sb.recipientID} 124 | //} 125 | 126 | spkB := b.SignedPreKeyPub 127 | if !Verify(b.IdentityKeyPub.Key, spkB.Key[:], b.SignedPreKeySignature) { 128 | return nil, fmt.Errorf("verify signed pre-key failed") 129 | } 130 | 131 | identityKeyPair, err := s.store.GetIdentityKeyPair() 132 | if err != nil { 133 | return nil, err 134 | } 135 | ikA := identityKeyPair.Priv 136 | ikB := b.IdentityKeyPub 137 | 138 | ephemeralKeyPair := GenerateEphemeralKeyPair() 139 | ekA := ephemeralKeyPair.Priv 140 | opkB := b.OneTimePreKeyPub 141 | 142 | s.ad = append(identityKeyPair.Pub.Key[:], b.IdentityKeyPub.Key[:]...) 143 | 144 | // SKAD 145 | dh1 := DH(ikA, spkB) 146 | dh2 := DH(ekA, ikB) 147 | dh3 := DH(ekA, spkB) 148 | dhList := [][]byte{dh1[:], dh2[:], dh3[:]} 149 | 150 | if opkB != nil { 151 | dh4 := DH(ekA, opkB) 152 | dhList = append(dhList, dh4[:]) 153 | } 154 | 155 | // TODO: Delete dh values 156 | s.sk = KDF(dhList...) 157 | 158 | s.identityKeyPub = identityKeyPair.Pub 159 | s.ephemeralKeyPub = ephemeralKeyPair.Pub 160 | 161 | s.signedPreKeyID = b.SignedPreKeyID 162 | s.oneTimePreKeyID = b.OneTimePreKeyID 163 | 164 | return s, nil 165 | } 166 | 167 | type AliceMessage struct { 168 | identityKeyPub *PubKey 169 | ephemeralKeyPub *PubKey 170 | 171 | signedPreKeyID uint32 172 | oneTimePreKeyID int32 173 | 174 | ciphertext []byte 175 | } 176 | 177 | func (s *SenderSession) sendFirstMessage(message []byte) (*AliceMessage, error) { 178 | var err error 179 | 180 | am := AliceMessage{ 181 | identityKeyPub: s.identityKeyPub, 182 | ephemeralKeyPub: s.ephemeralKeyPub, 183 | signedPreKeyID: s.signedPreKeyID, 184 | oneTimePreKeyID: s.oneTimePreKeyID, 185 | } 186 | if s.sk.index == 0 { 187 | am.ciphertext, err = EncryptAEAD(s.sk.chainKey[:], message, s.ad) 188 | if err != nil { 189 | return nil, err 190 | } 191 | return &am, nil 192 | } 193 | return nil, fmt.Errorf("chain index != 0 (%d)", s.sk.index) 194 | } 195 | 196 | type message struct { 197 | } 198 | 199 | func (s *SenderSession) sendNextMessage(message []byte) (*message, error) { 200 | /* 201 | mk, err := s.sk.getMessageKeys() 202 | if err != nil { 203 | return nil, err 204 | } 205 | 206 | ciphertext, err := Encrypt(mk.CipherKey, mk.Iv, message) 207 | if err != nil { 208 | return nil, err 209 | } 210 | 211 | fmt.Printf("%q", ciphertext) 212 | */ 213 | return nil, nil 214 | } 215 | 216 | type ReceiverSession struct { 217 | store Store 218 | 219 | sk *derivedKeys 220 | ad []byte 221 | 222 | ciphertext []byte 223 | } 224 | 225 | func NewReceiverSession(store Store, a *AliceMessage) (*ReceiverSession, error) { 226 | s := ReceiverSession{ 227 | store: store, 228 | ciphertext: a.ciphertext, 229 | } 230 | 231 | signedPreKey, err := s.store.GetSignedPreKey(a.signedPreKeyID) 232 | if err != nil { 233 | return nil, err 234 | } 235 | spkB := signedPreKey.Priv 236 | 237 | identityKeyPair, err := s.store.GetIdentityKeyPair() 238 | if err != nil { 239 | return nil, err 240 | } 241 | ikA := a.identityKeyPub 242 | ikB := identityKeyPair.Priv 243 | 244 | ekA := a.ephemeralKeyPub 245 | 246 | var opkB *PrivKey 247 | if a.oneTimePreKeyID != -1 { 248 | preKey, err := s.store.GetPreKey(uint32(a.oneTimePreKeyID)) 249 | if err != nil { 250 | return nil, err 251 | } 252 | opkB = preKey.Priv 253 | } 254 | 255 | s.ad = append(a.identityKeyPub.Key[:], identityKeyPair.Pub.Key[:]...) 256 | 257 | // SKAD 258 | dh1 := DH(spkB, ikA) 259 | dh2 := DH(ikB, ekA) 260 | dh3 := DH(spkB, ekA) 261 | dhList := [][]byte{dh1[:], dh2[:], dh3[:]} 262 | 263 | if opkB != nil { 264 | dh4 := DH(opkB, ekA) 265 | dhList = append(dhList, dh4[:]) 266 | } 267 | 268 | // TODO: Delete dh values 269 | s.sk = KDF(dhList...) 270 | return &s, nil 271 | } 272 | 273 | func (s *ReceiverSession) processFirstMessage() (string, error) { 274 | plaintext, err := DecryptAEAD(s.sk.chainKey[:], s.ciphertext, s.ad) 275 | if err != nil { 276 | return "", err 277 | } 278 | return string(plaintext), nil 279 | } 280 | -------------------------------------------------------------------------------- /store.go: -------------------------------------------------------------------------------- 1 | package signal 2 | 3 | type Store interface { 4 | GetIdentityKeyPair() (*KeyPair, error) 5 | 6 | PutIdentityKeyPair(keyPair *KeyPair) error 7 | 8 | GetLocalRegistrationID() (uint64, error) 9 | 10 | PutLocalRegistrationID(id uint64) error 11 | 12 | GetIdentityKey(keyID uint32) (*[32]byte, error) 13 | 14 | PutIdentityKey(keyID uint32, identityKey *[32]byte) error 15 | 16 | GetPreKey(keyID uint32) (*PreKey, error) 17 | 18 | PutPreKey(keyID uint32, preKey *PreKey) error 19 | 20 | GetSignedPreKey(keyID uint32) (*SignedPreKey, error) 21 | 22 | PutSignedPreKey(keyID uint32, signedPreKey *SignedPreKey) error 23 | } 24 | --------------------------------------------------------------------------------