?) {
49 | guard let add = address?.pointee else {
50 | return nil
51 | }
52 | self.init(from: add)
53 | }
54 |
55 | convenience init?(from address: signal_protocol_address) {
56 | guard let namePtr = address.name else {
57 | return nil
58 | }
59 | self.init(name: String(cString: namePtr), deviceId: address.device_id)
60 | }
61 |
62 | deinit {
63 | signalAddress.deallocate()
64 | }
65 | }
66 |
67 | extension SignalAddress: Equatable {
68 |
69 | /**
70 | Compare two signal addresses for equality
71 | - parameter lhs: The first address
72 | - parameter rhs: The second address
73 | - returns: `true` if the addresses match
74 | */
75 | public static func == (lhs: SignalAddress, rhs: SignalAddress) -> Bool {
76 | return lhs.name == rhs.name && lhs.deviceId == rhs.deviceId
77 | }
78 | }
79 |
80 | extension SignalAddress: Hashable {
81 |
82 | /// A hash of the address
83 | public var hashValue: Int {
84 | return name.hashValue &+ deviceId.hashValue
85 | }
86 | }
87 |
88 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/group_session_builder.h:
--------------------------------------------------------------------------------
1 | #ifndef GROUP_SESSION_BUILDER_H
2 | #define GROUP_SESSION_BUILDER_H
3 |
4 | #include "signal_protocol_types.h"
5 |
6 | #ifdef __cplusplus
7 | extern "C" {
8 | #endif
9 |
10 | /*
11 | * Group session builder is responsible for setting up group sender key encrypted sessions.
12 | *
13 | * Once a session has been established, group_cipher can be used to
14 | * encrypt/decrypt messages in that session.
15 | *
16 | * The built sessions are unidirectional: they can be used either for sending
17 | * or for receiving, but not both.
18 | *
19 | * Sessions are constructed per (groupId + senderId + deviceId) tuple. Remote logical users
20 | * are identified by their senderId, and each logical recipientId can have multiple physical
21 | * devices.
22 | */
23 |
24 | /**
25 | * Constructs a group session builder.
26 | *
27 | * The store and global contexts must remain valid for the lifetime of the
28 | * session builder.
29 | *
30 | * When finished, free the returned instance by calling group_session_builder_free().
31 | *
32 | * @param builder set to a freshly allocated group session builder instance
33 | * @param store the signal_protocol_store_context to store all state information in
34 | * @param global_context the global library context
35 | * @return 0 on success, or negative on failure
36 | */
37 | int group_session_builder_create(group_session_builder **builder,
38 | signal_protocol_store_context *store, signal_context *global_context);
39 |
40 | /**
41 | * Construct a group session for receiving messages from senderKeyName.
42 | *
43 | * @param sender_key_name the (groupId, senderId, deviceId) tuple associated
44 | * with the sender_key_distribution_message
45 | * @param distribution_message a received sender_key_distribution_message
46 | * @return 0 on success, or negative on failure
47 | */
48 | int group_session_builder_process_session(group_session_builder *builder,
49 | const signal_protocol_sender_key_name *sender_key_name,
50 | sender_key_distribution_message *distribution_message);
51 |
52 | /**
53 | * Construct a group session for sending messages.
54 | *
55 | * @param distribution_message a distribution message to be allocated and populated
56 | * @param sender_key_name the (groupId, senderId, deviceId) tuple. In this
57 | * case, the sender should be the caller
58 | * @return 0 on success, or negative on failure
59 | */
60 | int group_session_builder_create_session(group_session_builder *builder,
61 | sender_key_distribution_message **distribution_message,
62 | const signal_protocol_sender_key_name *sender_key_name);
63 |
64 | void group_session_builder_free(group_session_builder *builder);
65 |
66 | #ifdef __cplusplus
67 | }
68 | #endif
69 |
70 | #endif /* GROUP_SESSION_BUILDER_H */
71 |
--------------------------------------------------------------------------------
/libsignal-protocol-swiftTests/TestHelper.swift:
--------------------------------------------------------------------------------
1 | //
2 | // TestHelper.swift
3 | // libsignal-protocol-swiftTests
4 | //
5 | // Created by User on 19.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import SignalProtocol
10 |
11 | func setupStore(makeKeys: Bool) -> SignalStore? {
12 |
13 | let store: SignalStore
14 | do {
15 | store = try SignalStore(
16 | identityKeyStore: TestIdentityStore(),
17 | preKeyStore: TestPreKeyStore(),
18 | sessionStore: TestSessionStore(),
19 | signedPreKeyStore: TestSignedPrekeyStore(),
20 | senderKeyStore: TestSenderKeyStore())
21 | } catch {
22 | print("Failed to create store: \(error)")
23 | return nil
24 | }
25 |
26 | let identity: KeyPair
27 | do { identity = try Signal.generateIdentityKeyPair()
28 | } catch {
29 | print("Could not create identity key: \(error)")
30 | return nil
31 | }
32 |
33 | let registrationId: UInt32
34 | do {
35 | registrationId = try Signal.generateRegistrationId()
36 | } catch {
37 | print("Could not create registration id: \(error)")
38 | return nil
39 | }
40 |
41 | // Store identity key pair and registration id
42 | (store.identityKeyStore as! TestIdentityStore).identity = identity
43 | (store.identityKeyStore as! TestIdentityStore).registrationId = registrationId
44 |
45 | if makeKeys {
46 | let preKeys: [SessionPreKey]
47 | do {
48 | preKeys = try Signal.generatePreKeys(start: 1, count: 100)
49 | } catch {
50 | print("Could not create pre keys: \(error)")
51 | return nil
52 | }
53 |
54 | // Store keys
55 | for key in preKeys {
56 | do {
57 | let stored = store.preKeyStore.store(preKey: try key.data(), for: key.id)
58 | guard stored else {
59 | print("Could not store pre key")
60 | return nil
61 | }
62 | } catch {
63 | print("Could not serialize pre key: \(error)")
64 | return nil
65 | }
66 | }
67 |
68 | let signedPreKey: SessionSignedPreKey
69 | do {
70 | signedPreKey = try Signal.generate(signedPreKey: 1, identity: identity, timestamp: 0)
71 | } catch {
72 | print("Could not create signed pre key: \(error)")
73 | return nil
74 | }
75 |
76 | // Store signed pre key
77 | do {
78 | (store.signedPreKeyStore as! TestSignedPrekeyStore).keys[signedPreKey.id] = try signedPreKey.data()
79 | } catch {
80 | print("Could not serialize signed pre key: \(error)")
81 | }
82 | }
83 | /// Setup finished
84 | return store
85 | }
86 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/ge_double_scalarmult.c:
--------------------------------------------------------------------------------
1 | #include "ge.h"
2 |
3 | static void slide(signed char *r,const unsigned char *a)
4 | {
5 | int i;
6 | int b;
7 | int k;
8 |
9 | for (i = 0;i < 256;++i)
10 | r[i] = 1 & (a[i >> 3] >> (i & 7));
11 |
12 | for (i = 0;i < 256;++i)
13 | if (r[i]) {
14 | for (b = 1;b <= 6 && i + b < 256;++b) {
15 | if (r[i + b]) {
16 | if (r[i] + (r[i + b] << b) <= 15) {
17 | r[i] += r[i + b] << b; r[i + b] = 0;
18 | } else if (r[i] - (r[i + b] << b) >= -15) {
19 | r[i] -= r[i + b] << b;
20 | for (k = i + b;k < 256;++k) {
21 | if (!r[k]) {
22 | r[k] = 1;
23 | break;
24 | }
25 | r[k] = 0;
26 | }
27 | } else
28 | break;
29 | }
30 | }
31 | }
32 |
33 | }
34 |
35 | static ge_precomp Bi[8] = {
36 | #include "base2.h"
37 | } ;
38 |
39 | /*
40 | r = a * A + b * B
41 | where a = a[0]+256*a[1]+...+256^31 a[31].
42 | and b = b[0]+256*b[1]+...+256^31 b[31].
43 | B is the Ed25519 base point (x,4/5) with x positive.
44 | */
45 |
46 | void ge_double_scalarmult_vartime(ge_p2 *r,const unsigned char *a,const ge_p3 *A,const unsigned char *b)
47 | {
48 | signed char aslide[256];
49 | signed char bslide[256];
50 | ge_cached Ai[8]; /* A,3A,5A,7A,9A,11A,13A,15A */
51 | ge_p1p1 t;
52 | ge_p3 u;
53 | ge_p3 A2;
54 | int i;
55 |
56 | slide(aslide,a);
57 | slide(bslide,b);
58 |
59 | ge_p3_to_cached(&Ai[0],A);
60 | ge_p3_dbl(&t,A); ge_p1p1_to_p3(&A2,&t);
61 | ge_add(&t,&A2,&Ai[0]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[1],&u);
62 | ge_add(&t,&A2,&Ai[1]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[2],&u);
63 | ge_add(&t,&A2,&Ai[2]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[3],&u);
64 | ge_add(&t,&A2,&Ai[3]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[4],&u);
65 | ge_add(&t,&A2,&Ai[4]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[5],&u);
66 | ge_add(&t,&A2,&Ai[5]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[6],&u);
67 | ge_add(&t,&A2,&Ai[6]); ge_p1p1_to_p3(&u,&t); ge_p3_to_cached(&Ai[7],&u);
68 |
69 | ge_p2_0(r);
70 |
71 | for (i = 255;i >= 0;--i) {
72 | if (aslide[i] || bslide[i]) break;
73 | }
74 |
75 | for (;i >= 0;--i) {
76 | ge_p2_dbl(&t,r);
77 |
78 | if (aslide[i] > 0) {
79 | ge_p1p1_to_p3(&u,&t);
80 | ge_add(&t,&u,&Ai[aslide[i]/2]);
81 | } else if (aslide[i] < 0) {
82 | ge_p1p1_to_p3(&u,&t);
83 | ge_sub(&t,&u,&Ai[(-aslide[i])/2]);
84 | }
85 |
86 | if (bslide[i] > 0) {
87 | ge_p1p1_to_p3(&u,&t);
88 | ge_madd(&t,&u,&Bi[bslide[i]/2]);
89 | } else if (bslide[i] < 0) {
90 | ge_p1p1_to_p3(&u,&t);
91 | ge_msub(&t,&u,&Bi[(-bslide[i])/2]);
92 | }
93 |
94 | ge_p1p1_to_p2(r,&t);
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Setup/setup.c:
--------------------------------------------------------------------------------
1 | //
2 | // setup.c
3 | // libsignal-protocol-swift iOS
4 | //
5 | // Created by User on 15.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | #include "setup.h"
10 | #include "signal_protocol.h"
11 |
12 | #include
13 |
14 | pthread_mutex_t global_mutex;
15 | pthread_mutexattr_t global_mutex_attr;
16 |
17 | signal_protocol_store_context* setup_store_context(signal_context *global_context);
18 | int set_locking(signal_context *global_context);
19 | void test_log(int level, const char *message, size_t len, void *user_data);
20 |
21 | void *signal_setup(void) {
22 | signal_context *global_context;
23 | int result = signal_context_create(&global_context, 0);
24 | if (result != 0) {
25 | return 0;
26 | }
27 |
28 | result = set_locking(global_context);
29 | if (result != 0) {
30 | signal_context_destroy(global_context);
31 | return 0;
32 | }
33 |
34 | result = setup_crypto_provider(global_context);
35 | if (result != 0) {
36 | signal_context_destroy(global_context);
37 | pthread_mutex_destroy(&global_mutex);
38 | pthread_mutexattr_destroy(&global_mutex_attr);
39 | return 0;
40 | }
41 |
42 | signal_context_set_log_function(global_context, test_log);
43 |
44 | return (void*) global_context;
45 | }
46 |
47 | void signal_destroy(void *global_context) {
48 |
49 | signal_context_destroy((signal_context*) global_context);
50 |
51 | pthread_mutex_destroy(&global_mutex);
52 | pthread_mutexattr_destroy(&global_mutex_attr);
53 | }
54 |
55 | // MARK: Locking functions
56 |
57 | void test_lock(void *user_data) {
58 | pthread_mutex_lock(&global_mutex);
59 | }
60 |
61 | void test_unlock(void *user_data) {
62 | pthread_mutex_unlock(&global_mutex);
63 | }
64 |
65 | int set_locking(signal_context *global_context) {
66 | pthread_mutexattr_init(&global_mutex_attr);
67 | pthread_mutexattr_settype(&global_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
68 | pthread_mutex_init(&global_mutex, &global_mutex_attr);
69 |
70 | return signal_context_set_locking_functions(global_context, test_lock, test_unlock);
71 | }
72 |
73 | void test_log(int level, const char *message, size_t len, void *user_data) {
74 | switch(level) {
75 | case SG_LOG_ERROR:
76 | fprintf(stderr, "[ERROR] %s\n", message);
77 | break;
78 | case SG_LOG_WARNING:
79 | fprintf(stderr, "[WARNING] %s\n", message);
80 | break;
81 | case SG_LOG_NOTICE:
82 | fprintf(stderr, "[NOTICE] %s\n", message);
83 | break;
84 | case SG_LOG_INFO:
85 | fprintf(stderr, "[INFO] %s\n", message);
86 | break;
87 | case SG_LOG_DEBUG:
88 | fprintf(stderr, "[DEBUG] %s\n", message);
89 | break;
90 | default:
91 | fprintf(stderr, "[%d] %s\n", level, message);
92 | break;
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/additions/generalized/gen_eddsa.h:
--------------------------------------------------------------------------------
1 | #ifndef __GEN_EDDSA_H__
2 | #define __GEN_EDDSA_H__
3 |
4 | #include "ge.h"
5 |
6 | /* B: base point
7 | R: commitment (point),
8 | r: private nonce (scalar)
9 | K: encoded public key
10 | k: private key (scalar)
11 | Z: 32-bytes random
12 | M: buffer containing message, message starts at M_start, continues for M_len
13 |
14 | r = hash(B || labelset || Z || pad1 || k || pad2 || labelset || K || extra || M) (mod q)
15 | */
16 | int generalized_commit(unsigned char* R_bytes, unsigned char* r_scalar,
17 | const unsigned char* labelset, const unsigned long labelset_len,
18 | const unsigned char* extra, const unsigned long extra_len,
19 | const unsigned char* K_bytes, const unsigned char* k_scalar,
20 | const unsigned char* Z,
21 | unsigned char* M_buf, const unsigned long M_start, const unsigned long M_len);
22 |
23 | /* if is_labelset_empty(labelset):
24 | return hash(R || K || M) (mod q)
25 | else:
26 | return hash(B || labelset || R || labelset || K || extra || M) (mod q)
27 | */
28 | int generalized_challenge(unsigned char* h_scalar,
29 | const unsigned char* labelset, const unsigned long labelset_len,
30 | const unsigned char* extra, const unsigned long extra_len,
31 | const unsigned char* R_bytes,
32 | const unsigned char* K_bytes,
33 | unsigned char* M_buf, const unsigned long M_start, const unsigned long M_len);
34 |
35 | /* return r + kh (mod q) */
36 | int generalized_prove(unsigned char* out_scalar,
37 | const unsigned char* r_scalar,
38 | const unsigned char* k_scalar,
39 | const unsigned char* h_scalar);
40 |
41 | /* R = B^s / K^h */
42 | int generalized_solve_commitment(unsigned char* R_bytes_out, ge_p3* K_point_out,
43 | const ge_p3* B_point, const unsigned char* s_scalar,
44 | const unsigned char* K_bytes, const unsigned char* h_scalar);
45 |
46 |
47 | int generalized_eddsa_25519_sign(
48 | unsigned char* signature_out,
49 | const unsigned char* eddsa_25519_pubkey_bytes,
50 | const unsigned char* eddsa_25519_privkey_scalar,
51 | const unsigned char* msg,
52 | const unsigned long msg_len,
53 | const unsigned char* random,
54 | const unsigned char* customization_label,
55 | const unsigned long customization_label_len);
56 |
57 | int generalized_eddsa_25519_verify(
58 | const unsigned char* signature,
59 | const unsigned char* eddsa_25519_pubkey,
60 | const unsigned char* msg,
61 | const unsigned long msg_len,
62 | const unsigned char* customization_label,
63 | const unsigned long customization_label_len);
64 |
65 | #endif
66 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Misc/SignalError.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SignalError.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 16.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 |
11 | /**
12 | Errors thrown by the framework.
13 | - note: Most errors correspond directly to
14 | the error codes of `libsignal-protocol-c`.
15 | */
16 | public enum SignalError: Int32, Error {
17 |
18 | // MARK: libsignal-protocol-c errors
19 |
20 | /// Allocation of memory failed
21 | case noMemory = -12
22 |
23 | /// An argument to the function was invalid/missing
24 | case invalidArgument = -22
25 |
26 | /// Unspecified error
27 | case unknownError = -1000
28 |
29 | /// The message has already been received
30 | case duplicateMessage = -1001
31 |
32 | /// The key is invalid
33 | case invalidKey = -1002
34 |
35 | /// The key id is invalid
36 | case invalidKeyId = -1003
37 |
38 | /// The MAC of a message is invalid
39 | case invalidMac = -1004
40 |
41 | /// The message is malformed or corrupt
42 | case invalidMessage = -1005
43 |
44 | /// The version does not match
45 | case invalidVersion = -1006
46 |
47 | /// The message version is no longer supported
48 | case legacyMessage = -1007
49 |
50 | /// There is no session saved
51 | case noSession = -1008
52 |
53 | //case staleKeyExchange = -1009
54 |
55 | /// The identity of the sender is untrusted
56 | case untrustedIdentity = -1010
57 |
58 | /// The VRF signature is invalid
59 | case incalidVrfSignature = -1011
60 |
61 | /// The (de)serialization failed
62 | case invalidProtoBuf = -1100
63 |
64 | /// The fingerprint versions don't match
65 | case fpVersionMismatch = -1200
66 |
67 | /// The identities of the fingerprints don't match
68 | case fpIdentityMismatch = -1201
69 |
70 | // MARK: libsignal-protocol-swift errors
71 |
72 | /// There is no delegate registered
73 | case noDelegate = -2001
74 |
75 | /// No identity key or registration id in the identity key store
76 | case noData = -2002
77 |
78 | /// A Swift SignalAddress could not be created
79 | case noSignalAddress = -2003
80 |
81 | /// Retrieving data from a key store failed
82 | case notSuccessful = -2004
83 |
84 | /// An identity key could not be checked
85 | case isTrustedFailed = -2005
86 |
87 | /**
88 | Create a SignalError from a `libsignal-protocol-c` result.
89 | - note: For unknown error codes the error will be set to `unknownError`
90 | - parameter value: The result code of an operation.
91 | */
92 | public init(value: Int32) {
93 | if let status = SignalError(rawValue: Int32(value)) {
94 | self = status
95 | } else {
96 | print("Unknown error: \(value)")
97 | self = .unknownError
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Stores/SessionStore.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SessionStore.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 15.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | The `SessionStore`protocol must be adopted to provide the storage for sessions.
14 | */
15 | public protocol SessionStore {
16 |
17 | /**
18 | Returns a copy of the serialized session record corresponding to the
19 | provided recipient ID + device ID tuple.
20 |
21 | - parameter address: The address of the remote client
22 | - returns: The session and optional user record, or nil on failure
23 | */
24 | func loadSession(for address: SignalAddress) -> (session: Data, userRecord: Data?)?
25 |
26 | /**
27 | Returns all known devices with active sessions for a recipient
28 | - parameter name: The name of the remote client
29 | - returns: The ids of all active devices
30 | */
31 | func subDeviceSessions(for name: String) -> [Int32]?
32 |
33 | /**
34 | Commit to storage the session record for a given
35 | recipient ID + device ID tuple.
36 |
37 | - parameter session: The serialized session record
38 | - parameter userRecord: Application specific data to be stored alongside the serialized session record for the remote client. If no such data exists, then this parameter will be nil.
39 | - parameter address: The address of the remote client
40 | - returns: `true` on sucess, `false` on failure.
41 | */
42 | func store(session: Data, for address: SignalAddress, userRecord: Data?) -> Bool
43 |
44 | /**
45 | Determine whether there is a committed session record for a
46 | recipient ID + device ID tuple.
47 |
48 | - parameter address: The address of the remote client
49 | - returns: `true` if a session record exists, `false` otherwise.
50 | */
51 | func containsSession(for address: SignalAddress) -> Bool
52 |
53 | /**
54 | Remove a session record for a recipient ID + device ID tuple.
55 |
56 | - parameter address: The address of the remote client
57 | - returns: `true` if a session was deleted, `false` if a session was not deleted, nil on error
58 | */
59 | func deleteSession(for address: SignalAddress) -> Bool?
60 |
61 | /**
62 | Remove the session records corresponding to all devices of a recipient Id.
63 |
64 | - parameter name: The name of the remote client
65 | - returns: The number of deleted sessions on success, nil on failure
66 | */
67 | func deleteAllSessions(for name: String) -> Int?
68 |
69 | /**
70 | Function called to perform cleanup when the data store context is being
71 | destroyed.
72 | */
73 | func destroy()
74 | }
75 |
76 | public extension SessionStore {
77 |
78 | /**
79 | Function called to perform cleanup when the data store context is being
80 | destroyed.
81 | */
82 | func destroy() {
83 | // Empty implementation to make this function 'optional'
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/ge_scalarmult_base.c:
--------------------------------------------------------------------------------
1 | #include "ge.h"
2 | #include "crypto_uint32.h"
3 |
4 | static unsigned char equal(signed char b,signed char c)
5 | {
6 | unsigned char ub = b;
7 | unsigned char uc = c;
8 | unsigned char x = ub ^ uc; /* 0: yes; 1..255: no */
9 | crypto_uint32 y = x; /* 0: yes; 1..255: no */
10 | y -= 1; /* 4294967295: yes; 0..254: no */
11 | y >>= 31; /* 1: yes; 0: no */
12 | return y;
13 | }
14 |
15 | static unsigned char negative(signed char b)
16 | {
17 | unsigned long long x = b; /* 18446744073709551361..18446744073709551615: yes; 0..255: no */
18 | x >>= 63; /* 1: yes; 0: no */
19 | return x;
20 | }
21 |
22 | static void cmov(ge_precomp *t,ge_precomp *u,unsigned char b)
23 | {
24 | fe_cmov(t->yplusx,u->yplusx,b);
25 | fe_cmov(t->yminusx,u->yminusx,b);
26 | fe_cmov(t->xy2d,u->xy2d,b);
27 | }
28 |
29 | /* base[i][j] = (j+1)*256^i*B */
30 | static ge_precomp base[32][8] = {
31 | #include "base.h"
32 | } ;
33 |
34 | static void select(ge_precomp *t,int pos,signed char b)
35 | {
36 | ge_precomp minust;
37 | unsigned char bnegative = negative(b);
38 | unsigned char babs = b - (((-bnegative) & b) << 1);
39 |
40 | ge_precomp_0(t);
41 | cmov(t,&base[pos][0],equal(babs,1));
42 | cmov(t,&base[pos][1],equal(babs,2));
43 | cmov(t,&base[pos][2],equal(babs,3));
44 | cmov(t,&base[pos][3],equal(babs,4));
45 | cmov(t,&base[pos][4],equal(babs,5));
46 | cmov(t,&base[pos][5],equal(babs,6));
47 | cmov(t,&base[pos][6],equal(babs,7));
48 | cmov(t,&base[pos][7],equal(babs,8));
49 | fe_copy(minust.yplusx,t->yminusx);
50 | fe_copy(minust.yminusx,t->yplusx);
51 | fe_neg(minust.xy2d,t->xy2d);
52 | cmov(t,&minust,bnegative);
53 | }
54 |
55 | /*
56 | h = a * B
57 | where a = a[0]+256*a[1]+...+256^31 a[31]
58 | B is the Ed25519 base point (x,4/5) with x positive.
59 |
60 | Preconditions:
61 | a[31] <= 127
62 | */
63 |
64 | void ge_scalarmult_base(ge_p3 *h,const unsigned char *a)
65 | {
66 | signed char e[64];
67 | signed char carry;
68 | ge_p1p1 r;
69 | ge_p2 s;
70 | ge_precomp t;
71 | int i;
72 |
73 | for (i = 0;i < 32;++i) {
74 | e[2 * i + 0] = (a[i] >> 0) & 15;
75 | e[2 * i + 1] = (a[i] >> 4) & 15;
76 | }
77 | /* each e[i] is between 0 and 15 */
78 | /* e[63] is between 0 and 7 */
79 |
80 | carry = 0;
81 | for (i = 0;i < 63;++i) {
82 | e[i] += carry;
83 | carry = e[i] + 8;
84 | carry >>= 4;
85 | e[i] -= carry << 4;
86 | }
87 | e[63] += carry;
88 | /* each e[i] is between -8 and 8 */
89 |
90 | ge_p3_0(h);
91 | for (i = 1;i < 64;i += 2) {
92 | select(&t,i / 2,e[i]);
93 | ge_madd(&r,h,&t); ge_p1p1_to_p3(h,&r);
94 | }
95 |
96 | ge_p3_dbl(&r,h); ge_p1p1_to_p2(&s,&r);
97 | ge_p2_dbl(&r,&s); ge_p1p1_to_p2(&s,&r);
98 | ge_p2_dbl(&r,&s); ge_p1p1_to_p2(&s,&r);
99 | ge_p2_dbl(&r,&s); ge_p1p1_to_p3(h,&r);
100 |
101 | for (i = 0;i < 64;i += 2) {
102 | select(&t,i / 2,e[i]);
103 | ge_madd(&r,h,&t); ge_p1p1_to_p3(h,&r);
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Misc/SignalSenderKeyName.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SignalSenderKeyName.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 15.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | The identifier of a party in a group conversation setting.
14 | */
15 | public final class SignalSenderKeyName {
16 |
17 | /// The group identifier
18 | public let groupId: String
19 |
20 | /// The sender/recipient
21 | public let sender: SignalAddress
22 |
23 | private let groupPointer: UnsafeMutablePointer
24 |
25 | private let address: UnsafeMutablePointer
26 |
27 | var pointer: UnsafePointer {
28 | return UnsafePointer(address)
29 | }
30 |
31 | /**
32 | Create a sender key name.
33 | - parameter groupId: the identifier of the group
34 | - parameter sender: The sender of the messages
35 | */
36 | public init(groupId: String, sender: SignalAddress) {
37 | self.groupId = groupId
38 | self.sender = sender
39 | let count = groupId.utf8.count
40 | self.groupPointer = UnsafeMutablePointer.allocate(capacity: count)
41 | groupPointer.assign(from: groupId, count: count)
42 | self.address = UnsafeMutablePointer.allocate(capacity: 1)
43 |
44 | address.pointee = signal_protocol_sender_key_name(group_id: groupPointer, group_id_len: count, sender: sender.signalAddress.pointee)
45 | }
46 |
47 | /**
48 | Create an a sender key name from a pointer to a libsignal-protocol-c address.
49 | - parameter address: The pointer to the address
50 | */
51 | convenience init?(from address: UnsafePointer?) {
52 | guard let add = address?.pointee else {
53 | return nil
54 | }
55 | self.init(from: add)
56 | }
57 |
58 | /**
59 | Create an a sender key name from a libsignal-protocol-c address.
60 | - parameter address: The libsignal-protocol-c address
61 | */
62 | convenience init?(from address: signal_protocol_sender_key_name) {
63 |
64 | guard let groupPtr = address.group_id,
65 | let sender = SignalAddress(from: address.sender) else {
66 | return nil
67 | }
68 | self.init(groupId: String(cString: groupPtr), sender: sender)
69 | }
70 | }
71 |
72 | extension SignalSenderKeyName: Equatable {
73 |
74 | /**
75 | Compare two sender key names for equality
76 | - parameter lhs: The first address
77 | - parameter rhs: The second address
78 | - returns: `true` if the sender key names match
79 | */
80 | public static func == (lhs: SignalSenderKeyName, rhs: SignalSenderKeyName) -> Bool {
81 | return lhs.groupId == rhs.groupId && lhs.sender == rhs.sender
82 | }
83 |
84 | }
85 |
86 | extension SignalSenderKeyName: Hashable {
87 |
88 | /// The hash of the sender key name
89 | public var hashValue: Int {
90 | return groupId.hashValue &+ sender.hashValue
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/device_consistency.h:
--------------------------------------------------------------------------------
1 | #ifndef DEVICE_CONSISTENCY_H
2 | #define DEVICE_CONSISTENCY_H
3 |
4 | #include "signal_protocol_types.h"
5 |
6 | #ifdef __cplusplus
7 | extern "C" {
8 | #endif
9 |
10 | int device_consistency_signature_create(device_consistency_signature **signature,
11 | const uint8_t *signature_data, size_t signature_len,
12 | const uint8_t *vrf_output_data, size_t vrf_output_len);
13 |
14 | signal_buffer *device_consistency_signature_get_signature(const device_consistency_signature *signature);
15 | signal_buffer *device_consistency_signature_get_vrf_output(const device_consistency_signature *signature);
16 |
17 | void device_consistency_signature_destroy(signal_type_base *type);
18 |
19 | int device_consistency_commitment_create(device_consistency_commitment **commitment,
20 | uint32_t generation, ec_public_key_list *identity_key_list,
21 | signal_context *global_context);
22 |
23 | uint32_t device_consistency_commitment_get_generation(const device_consistency_commitment *commitment);
24 | signal_buffer *device_consistency_commitment_get_serialized(const device_consistency_commitment *commitment);
25 |
26 | void device_consistency_commitment_destroy(signal_type_base *type);
27 |
28 | int device_consistency_message_create_from_pair(device_consistency_message **message,
29 | device_consistency_commitment *commitment,
30 | ec_key_pair *identity_key_pair,
31 | signal_context *global_context);
32 | int device_consistency_message_create_from_serialized(device_consistency_message **message,
33 | device_consistency_commitment *commitment,
34 | const uint8_t *serialized_data, size_t serialized_len,
35 | ec_public_key *identity_key,
36 | signal_context *global_context);
37 |
38 | signal_buffer *device_consistency_message_get_serialized(const device_consistency_message *message);
39 | device_consistency_signature *device_consistency_message_get_signature(const device_consistency_message *message);
40 | uint32_t device_consistency_signature_get_generation(const device_consistency_message *message);
41 |
42 | void device_consistency_message_destroy(signal_type_base *type);
43 |
44 | int device_consistency_code_generate_for(device_consistency_commitment *commitment,
45 | device_consistency_signature_list *signatures,
46 | char **code_string,
47 | signal_context *global_context);
48 |
49 | device_consistency_signature_list *device_consistency_signature_list_alloc(void);
50 | device_consistency_signature_list *device_consistency_signature_list_copy(const device_consistency_signature_list *list);
51 | int device_consistency_signature_list_push_back(device_consistency_signature_list *list, device_consistency_signature *value);
52 | unsigned int device_consistency_signature_list_size(const device_consistency_signature_list *list);
53 | device_consistency_signature *device_consistency_signature_list_at(const device_consistency_signature_list *list, unsigned int index);
54 | void device_consistency_signature_list_free(device_consistency_signature_list *list);
55 |
56 | #ifdef __cplusplus
57 | }
58 | #endif
59 |
60 | #endif /* DEVICE_CONSISTENCY_H */
61 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/ge.h:
--------------------------------------------------------------------------------
1 | #ifndef GE_H
2 | #define GE_H
3 |
4 | /*
5 | ge means group element.
6 |
7 | Here the group is the set of pairs (x,y) of field elements (see fe.h)
8 | satisfying -x^2 + y^2 = 1 + d x^2y^2
9 | where d = -121665/121666.
10 |
11 | Representations:
12 | ge_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z
13 | ge_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT
14 | ge_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T
15 | ge_precomp (Duif): (y+x,y-x,2dxy)
16 | */
17 |
18 | #include "fe.h"
19 |
20 | typedef struct {
21 | fe X;
22 | fe Y;
23 | fe Z;
24 | } ge_p2;
25 |
26 | typedef struct {
27 | fe X;
28 | fe Y;
29 | fe Z;
30 | fe T;
31 | } ge_p3;
32 |
33 | typedef struct {
34 | fe X;
35 | fe Y;
36 | fe Z;
37 | fe T;
38 | } ge_p1p1;
39 |
40 | typedef struct {
41 | fe yplusx;
42 | fe yminusx;
43 | fe xy2d;
44 | } ge_precomp;
45 |
46 | typedef struct {
47 | fe YplusX;
48 | fe YminusX;
49 | fe Z;
50 | fe T2d;
51 | } ge_cached;
52 |
53 | #define ge_frombytes_negate_vartime crypto_sign_ed25519_ref10_ge_frombytes_negate_vartime
54 | #define ge_tobytes crypto_sign_ed25519_ref10_ge_tobytes
55 | #define ge_p3_tobytes crypto_sign_ed25519_ref10_ge_p3_tobytes
56 |
57 | #define ge_p2_0 crypto_sign_ed25519_ref10_ge_p2_0
58 | #define ge_p3_0 crypto_sign_ed25519_ref10_ge_p3_0
59 | #define ge_precomp_0 crypto_sign_ed25519_ref10_ge_precomp_0
60 | #define ge_p3_to_p2 crypto_sign_ed25519_ref10_ge_p3_to_p2
61 | #define ge_p3_to_cached crypto_sign_ed25519_ref10_ge_p3_to_cached
62 | #define ge_p1p1_to_p2 crypto_sign_ed25519_ref10_ge_p1p1_to_p2
63 | #define ge_p1p1_to_p3 crypto_sign_ed25519_ref10_ge_p1p1_to_p3
64 | #define ge_p2_dbl crypto_sign_ed25519_ref10_ge_p2_dbl
65 | #define ge_p3_dbl crypto_sign_ed25519_ref10_ge_p3_dbl
66 |
67 | #define ge_madd crypto_sign_ed25519_ref10_ge_madd
68 | #define ge_msub crypto_sign_ed25519_ref10_ge_msub
69 | #define ge_add crypto_sign_ed25519_ref10_ge_add
70 | #define ge_sub crypto_sign_ed25519_ref10_ge_sub
71 | #define ge_scalarmult_base crypto_sign_ed25519_ref10_ge_scalarmult_base
72 | #define ge_double_scalarmult_vartime crypto_sign_ed25519_ref10_ge_double_scalarmult_vartime
73 |
74 | extern void ge_tobytes(unsigned char *,const ge_p2 *);
75 | extern void ge_p3_tobytes(unsigned char *,const ge_p3 *);
76 | extern int ge_frombytes_negate_vartime(ge_p3 *,const unsigned char *);
77 |
78 | extern void ge_p2_0(ge_p2 *);
79 | extern void ge_p3_0(ge_p3 *);
80 | extern void ge_precomp_0(ge_precomp *);
81 | extern void ge_p3_to_p2(ge_p2 *,const ge_p3 *);
82 | extern void ge_p3_to_cached(ge_cached *,const ge_p3 *);
83 | extern void ge_p1p1_to_p2(ge_p2 *,const ge_p1p1 *);
84 | extern void ge_p1p1_to_p3(ge_p3 *,const ge_p1p1 *);
85 | extern void ge_p2_dbl(ge_p1p1 *,const ge_p2 *);
86 | extern void ge_p3_dbl(ge_p1p1 *,const ge_p3 *);
87 |
88 | extern void ge_madd(ge_p1p1 *,const ge_p3 *,const ge_precomp *);
89 | extern void ge_msub(ge_p1p1 *,const ge_p3 *,const ge_precomp *);
90 | extern void ge_add(ge_p1p1 *,const ge_p3 *,const ge_cached *);
91 | extern void ge_sub(ge_p1p1 *,const ge_p3 *,const ge_cached *);
92 | extern void ge_scalarmult_base(ge_p3 *,const unsigned char *);
93 | extern void ge_double_scalarmult_vartime(ge_p2 *,const unsigned char *,const ge_p3 *,const unsigned char *);
94 |
95 | #endif
96 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/session_pre_key.h:
--------------------------------------------------------------------------------
1 | #ifndef SESSION_PRE_KEY_H
2 | #define SESSION_PRE_KEY_H
3 |
4 | #include
5 | #include
6 | #include "signal_protocol_types.h"
7 |
8 | #ifdef __cplusplus
9 | extern "C" {
10 | #endif
11 |
12 | #define PRE_KEY_MEDIUM_MAX_VALUE 0xFFFFFF
13 |
14 | /*------------------------------------------------------------------------*/
15 |
16 | int session_pre_key_create(session_pre_key **pre_key, uint32_t id, ec_key_pair *key_pair);
17 | int session_pre_key_serialize(signal_buffer **buffer, const session_pre_key *pre_key);
18 | int session_pre_key_deserialize(session_pre_key **pre_key, const uint8_t *data, size_t len, signal_context *global_context);
19 |
20 | uint32_t session_pre_key_get_id(const session_pre_key *pre_key);
21 | ec_key_pair *session_pre_key_get_key_pair(const session_pre_key *pre_key);
22 |
23 | void session_pre_key_destroy(signal_type_base *type);
24 |
25 | /*------------------------------------------------------------------------*/
26 |
27 | int session_signed_pre_key_create(session_signed_pre_key **pre_key,
28 | uint32_t id, uint64_t timestamp, ec_key_pair *key_pair,
29 | const uint8_t *signature, size_t signature_len);
30 | int session_signed_pre_key_serialize(signal_buffer **buffer, const session_signed_pre_key *pre_key);
31 | int session_signed_pre_key_deserialize(session_signed_pre_key **pre_key, const uint8_t *data, size_t len, signal_context *global_context);
32 |
33 | uint32_t session_signed_pre_key_get_id(const session_signed_pre_key *pre_key);
34 | uint64_t session_signed_pre_key_get_timestamp(const session_signed_pre_key *pre_key);
35 | ec_key_pair *session_signed_pre_key_get_key_pair(const session_signed_pre_key *pre_key);
36 | const uint8_t *session_signed_pre_key_get_signature(const session_signed_pre_key *pre_key);
37 | size_t session_signed_pre_key_get_signature_len(const session_signed_pre_key *pre_key);
38 |
39 | void session_signed_pre_key_destroy(signal_type_base *type);
40 |
41 | /*------------------------------------------------------------------------*/
42 |
43 | int session_pre_key_bundle_create(session_pre_key_bundle **bundle,
44 | uint32_t registration_id, int device_id, uint32_t pre_key_id,
45 | ec_public_key *pre_key_public,
46 | uint32_t signed_pre_key_id, ec_public_key *signed_pre_key_public,
47 | const uint8_t *signed_pre_key_signature_data, size_t signed_pre_key_signature_len,
48 | ec_public_key *identity_key);
49 |
50 | uint32_t session_pre_key_bundle_get_registration_id(const session_pre_key_bundle *bundle);
51 | int session_pre_key_bundle_get_device_id(const session_pre_key_bundle *bundle);
52 | uint32_t session_pre_key_bundle_get_pre_key_id(const session_pre_key_bundle *bundle);
53 | ec_public_key *session_pre_key_bundle_get_pre_key(const session_pre_key_bundle *bundle);
54 | uint32_t session_pre_key_bundle_get_signed_pre_key_id(const session_pre_key_bundle *bundle);
55 | ec_public_key *session_pre_key_bundle_get_signed_pre_key(const session_pre_key_bundle *bundle);
56 | signal_buffer *session_pre_key_bundle_get_signed_pre_key_signature(const session_pre_key_bundle *bundle);
57 | ec_public_key *session_pre_key_bundle_get_identity_key(const session_pre_key_bundle *bundle);
58 |
59 | void session_pre_key_bundle_destroy(signal_type_base *type);
60 |
61 | #ifdef __cplusplus
62 | }
63 | #endif
64 |
65 | #endif /* SESSION_PRE_KEY_H */
66 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Sessions/SessionPreKeyBundle.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SessionPreKeyBundle.swift
3 | // libsignal-protocol-swift iOS
4 | //
5 | // Created by User on 16.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | A session pre key bundle can be used to establish a new session.
14 | */
15 | public struct SessionPreKeyBundle {
16 |
17 | /// The registration id of the remote party
18 | let registrationId: UInt32
19 |
20 | /// The device id of the remote party
21 | let deviceId: Int32
22 |
23 | /// The pre key id
24 | let preKeyId: UInt32
25 |
26 | /// The pre key public data
27 | let preKey: Data
28 |
29 | /// The signed pre key id
30 | let signedPreKeyId: UInt32
31 |
32 | /// The signed pre key public data
33 | let signedPreKey: Data
34 |
35 | /// The signature of the signed pre key
36 | let signature: Data
37 |
38 | /// The identity public key of the remote party
39 | let identityKey: Data
40 |
41 | /**
42 | Create a pre key bundle from the components
43 | - parameter registrationId: The registration id of the remote party
44 | - parameter deviceId: The device id of the remote party
45 | - parameter preKeyId: The pre key id
46 | - parameter preKey: The pre key public data
47 | - parameter signedPreKeyId: The signed pre key id
48 | - parameter signedPreKey: The signed pre key public data
49 | - parameter signature: The signature of the signed pre key
50 | - parameter identityKey: The identity public key of the remote party
51 | */
52 | public init(registrationId: UInt32,
53 | deviceId: Int32,
54 | preKeyId: UInt32,
55 | preKey: Data,
56 | signedPreKeyId: UInt32,
57 | signedPreKey: Data,
58 | signature: Data,
59 | identityKey: Data) {
60 | self.registrationId = registrationId
61 | self.deviceId = deviceId
62 | self.preKeyId = preKeyId
63 | self.preKey = preKey
64 | self.signedPreKeyId = signedPreKeyId
65 | self.signedPreKey = signedPreKey
66 | self.signature = signature
67 | self.identityKey = identityKey
68 | }
69 |
70 | /// Convert the bundle to a `session_pre_key_bundle` pointer (needs to be freed)
71 | func pointer() throws -> OpaquePointer {
72 |
73 | // Convert pre key
74 | let preKeyPtr = try preKey.publicKeyPointer()
75 | defer { signal_type_unref(preKeyPtr) }
76 |
77 | // Convert signed pre key
78 | let signedPreKeyPtr = try signedPreKey.publicKeyPointer()
79 | defer { signal_type_unref(signedPreKeyPtr) }
80 |
81 | // Convert identity key
82 | let identityKeyPtr = try identityKey.publicKeyPointer()
83 | defer { signal_type_unref(identityKeyPtr) }
84 |
85 | var bundlePtr: OpaquePointer? = nil
86 | let result = signature.withUnsafeBytes { ptr in
87 | withUnsafeMutablePointer(to: &bundlePtr) { bPtr in
88 | session_pre_key_bundle_create( bPtr, registrationId, deviceId, preKeyId, preKeyPtr, signedPreKeyId, signedPreKeyPtr, ptr, signature.count, identityKeyPtr)
89 | }
90 | }
91 | guard result == 0 else { throw SignalError(value: result) }
92 | return bundlePtr!
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Sessions/SessionSignedPreKey.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SessionSignedPreKey.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 16.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | A signed pre key.
14 | */
15 | public struct SessionSignedPreKey {
16 |
17 | /// The id of the signed pre key
18 | public let id: UInt32
19 |
20 | /// The creation timestamp of the key
21 | public let timestamp: UInt64
22 |
23 | /// The signature of the public key signed by the identity key
24 | public let signature: Data
25 |
26 | /// The key pair of the signed pre key
27 | public let keyPair: KeyPair
28 |
29 | /**
30 | Create a signed pre key from serialized data.
31 | - parameter data: The serialized data
32 | - throws: Errors of type `SignalError`
33 | */
34 | public init(from data: Data) throws {
35 | var signedPreKey: OpaquePointer? = nil
36 | let result = data.withUnsafeBytes { dPtr in
37 | withUnsafeMutablePointer(to: &signedPreKey) {
38 | session_signed_pre_key_deserialize($0, dPtr, data.count, Signal.context)
39 | }
40 | }
41 | guard result == 0 else { throw SignalError(value: result) }
42 | defer { session_signed_pre_key_destroy(signedPreKey) }
43 | try self.init(pointer: signedPreKey!)
44 | }
45 |
46 | /**
47 | Create a key pair from a pointer.
48 | - parameter pointer: A `session_signed_pre_key` pointer
49 | - throws: Errors of type `SignalError`
50 | */
51 | init(pointer: OpaquePointer) throws {
52 |
53 | let ptr = session_signed_pre_key_get_key_pair(pointer)!
54 | self.keyPair = try KeyPair(pointer: ptr)
55 |
56 | let signatureData = session_signed_pre_key_get_signature(pointer)
57 | let signatureLength = session_signed_pre_key_get_signature_len(pointer)
58 | guard signatureData != nil else { throw SignalError.unknownError }
59 | self.signature = Data(from: signatureData!, length: signatureLength)
60 | self.timestamp = session_signed_pre_key_get_timestamp(pointer)
61 | self.id = session_signed_pre_key_get_id(pointer)
62 | }
63 |
64 | /// Serialize the session signed pre key
65 | public func data() throws -> Data {
66 | let keyPairPtr = try keyPair.pointer()
67 | defer { ec_key_pair_destroy(keyPairPtr) }
68 |
69 | // Create pre key
70 | var signedPreKey: OpaquePointer? = nil
71 | var result = signature.withUnsafeBytes { ptr in
72 | withUnsafeMutablePointer(to: &signedPreKey) {
73 | return session_signed_pre_key_create($0, id, timestamp, keyPairPtr, ptr, signature.count)
74 | }
75 | }
76 | guard result == 0 else { throw SignalError(value: result) }
77 | defer { session_signed_pre_key_destroy(signedPreKey) }
78 |
79 | // Serialize pre key
80 | var signedPreKeyRecord: OpaquePointer? = nil
81 | result = withUnsafeMutablePointer(to: &signedPreKeyRecord) {
82 | session_signed_pre_key_serialize($0, signedPreKey)
83 | }
84 | guard result == 0 else { throw SignalError(value: result) }
85 | defer { signal_buffer_free(signedPreKeyRecord) }
86 |
87 | // Return serialized data
88 | return Data(signalBuffer: signedPreKeyRecord!)
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Misc/KeyPair.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyPair.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 16.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | A key pair consists of an elliptic curve public key and corresponding private key.
14 | */
15 | public struct KeyPair {
16 |
17 | /// The public key data
18 | public let publicKey: Data
19 |
20 | /// The private key data
21 | public let privateKey: Data
22 |
23 | /**
24 | Create a key pair from the components.
25 | - parameter publicKey: The public key data
26 | - parameter privateKey: The private key data
27 | */
28 | public init(publicKey: Data, privateKey: Data) {
29 | self.publicKey = publicKey
30 | self.privateKey = privateKey
31 | }
32 |
33 | /**
34 | Create a key pair from a pointer.
35 | - parameter pointer: The ec_key_pair pointer.
36 | - throws: Errors of type `SignalError`
37 | */
38 | init(pointer: OpaquePointer) throws {
39 | let pubKey = ec_key_pair_get_public(pointer)!
40 | let privKey = ec_key_pair_get_private(pointer)!
41 |
42 | var pubBuffer: OpaquePointer? = nil
43 | var result = withUnsafeMutablePointer(to: &pubBuffer) {
44 | ec_public_key_serialize($0, pubKey)
45 | }
46 | guard result == 0 else { throw SignalError(value: result) }
47 |
48 | var privBuffer: OpaquePointer? = nil
49 | result = withUnsafeMutablePointer(to: &privBuffer) {
50 | ec_private_key_serialize($0, privKey)
51 | }
52 | guard result == 0 else { throw SignalError(value: result) }
53 |
54 | self.publicKey = Data(signalBuffer: pubBuffer!)
55 | self.privateKey = Data(signalBuffer: privBuffer!)
56 | signal_buffer_free(pubBuffer)
57 | signal_buffer_free(privBuffer)
58 | }
59 |
60 | /// Convert to a pointer (must be freed through ec_key_pair_destroy)
61 | func pointer() throws -> OpaquePointer {
62 | // Convert public key
63 | let publicBuffer = publicKey.signalBuffer
64 | defer { signal_buffer_free(publicBuffer) }
65 | let pubLength = signal_buffer_len(publicBuffer)
66 | let pubData = signal_buffer_data(publicBuffer)!
67 | var pubKey: OpaquePointer? = nil
68 | var result = withUnsafeMutablePointer(to: &pubKey) {
69 | curve_decode_point($0, pubData, pubLength, Signal.context)
70 | }
71 | guard result == 0 else { throw SignalError(value: result) }
72 |
73 | // Convert private key
74 | let privateBuffer = privateKey.signalBuffer
75 | defer { signal_buffer_free(privateBuffer) }
76 | let privLength = signal_buffer_len(privateBuffer)
77 | let privData = signal_buffer_data(privateBuffer)!
78 | var privKey: OpaquePointer? = nil
79 | result = withUnsafeMutablePointer(to: &privKey) {
80 | curve_decode_private_point($0, privData, privLength, Signal.context)
81 | }
82 | guard result == 0 else { throw SignalError(value: result) }
83 |
84 | // Create key pair
85 | var keyPair: OpaquePointer? = nil
86 | result = withUnsafeMutablePointer(to: &keyPair) {
87 | ec_key_pair_create($0, pubKey, privKey)
88 | }
89 | guard result == 0 else { throw SignalError(value: result) }
90 | return keyPair!
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Misc/CiphertextMessage.swift:
--------------------------------------------------------------------------------
1 | //
2 | // CiphertextMessage.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 16.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | A `CiphertextMessage` is an encrypted message ready for delivery. It can be one
14 | of several types.
15 | */
16 | public struct CiphertextMessage {
17 |
18 | /// The message type of an encrypted message
19 | public enum MessageType: UInt8 {
20 |
21 | /// A signal message
22 | case signal = 2
23 |
24 | /// A pre key signal message to establish a session
25 | case preKey = 3
26 |
27 | /// A sender key message
28 | case senderKey = 4
29 |
30 | /// A sender key distribution message to esatblish a group session
31 | case distribution = 5
32 |
33 | /// Unknown message type
34 | case unknown
35 |
36 | /**
37 | Create a ciphertext message type from an Int32 value.
38 | - note: If the type value does not correspond to a recognised
39 | type, then the type will be `unknown`
40 | - parameter value: The raw value of the type
41 | */
42 | init(_ value: Int32) {
43 | switch value {
44 | case 2...5: self = MessageType(rawValue: UInt8(value))!
45 | default: self = .unknown
46 | }
47 | }
48 |
49 | /**
50 | Create a ciphertext message type from a UInt8 value.
51 | - note: If the type value does not correspond to a recognised
52 | type, then the type will be `unknown`
53 | - parameter value: The raw value of the type
54 | */
55 | init(_ value: UInt8) {
56 | switch value {
57 | case 2...5: self = MessageType(rawValue: value)!
58 | default: self = .unknown
59 | }
60 | }
61 | }
62 |
63 | /// The type of the message
64 | public let type: MessageType
65 |
66 | /// The message data
67 | public let message: Data
68 |
69 | /**
70 | Create a CiphertextMessage from type and data.
71 | - parameter type: The message type
72 | - parameter data: The encrypted data
73 | */
74 | public init(type: MessageType, message: Data) {
75 | self.type = type
76 | self.message = message
77 | }
78 |
79 | /**
80 | Create a message from a `ciphertext_message` pointer
81 | */
82 | init(pointer: OpaquePointer) {
83 | let messageType = ciphertext_message_get_type(pointer)
84 | self.type = MessageType(messageType)
85 | let ptr = ciphertext_message_get_serialized(pointer)
86 | self.message = Data(signalBuffer: ptr!)
87 | }
88 |
89 | /**
90 | Create a message from serialized data.
91 | - parameter data: The serialized message, containing the message type at the first byte.
92 | */
93 | public init(from data: Data) {
94 | guard data.count > 0 else {
95 | self.type = .unknown
96 | self.message = Data()
97 | return
98 | }
99 | self.type = MessageType(data[0])
100 | self.message = data.advanced(by: 1)
101 | }
102 |
103 | /// Serialize the message by prepending the message type to the message data
104 | public var data: Data {
105 | return [type.rawValue] + message
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/additions/curve_sigs.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "ge.h"
4 | #include "curve_sigs.h"
5 | #include "crypto_sign.h"
6 | #include "crypto_additions.h"
7 |
8 | int curve25519_sign(unsigned char* signature_out,
9 | const unsigned char* curve25519_privkey,
10 | const unsigned char* msg, const unsigned long msg_len,
11 | const unsigned char* random)
12 | {
13 | ge_p3 ed_pubkey_point; /* Ed25519 pubkey point */
14 | unsigned char ed_pubkey[32]; /* Ed25519 encoded pubkey */
15 | unsigned char *sigbuf; /* working buffer */
16 | unsigned char sign_bit = 0;
17 |
18 | if ((sigbuf = malloc(msg_len + 128)) == 0) {
19 | memset(signature_out, 0, 64);
20 | return -1;
21 | }
22 |
23 | /* Convert the Curve25519 privkey to an Ed25519 public key */
24 | ge_scalarmult_base(&ed_pubkey_point, curve25519_privkey);
25 | ge_p3_tobytes(ed_pubkey, &ed_pubkey_point);
26 | sign_bit = ed_pubkey[31] & 0x80;
27 |
28 | /* Perform an Ed25519 signature with explicit private key */
29 | crypto_sign_modified(sigbuf, msg, msg_len, curve25519_privkey,
30 | ed_pubkey, random);
31 | memmove(signature_out, sigbuf, 64);
32 |
33 | /* Encode the sign bit into signature (in unused high bit of S) */
34 | signature_out[63] &= 0x7F; /* bit should be zero already, but just in case */
35 | signature_out[63] |= sign_bit;
36 |
37 | free(sigbuf);
38 | return 0;
39 | }
40 |
41 | int curve25519_verify(const unsigned char* signature,
42 | const unsigned char* curve25519_pubkey,
43 | const unsigned char* msg, const unsigned long msg_len)
44 | {
45 | fe u;
46 | fe y;
47 | unsigned char ed_pubkey[32];
48 | unsigned char *verifybuf = NULL; /* working buffer */
49 | unsigned char *verifybuf2 = NULL; /* working buffer #2 */
50 | int result;
51 |
52 | if ((verifybuf = malloc(msg_len + 64)) == 0) {
53 | result = -1;
54 | goto err;
55 | }
56 |
57 | if ((verifybuf2 = malloc(msg_len + 64)) == 0) {
58 | result = -1;
59 | goto err;
60 | }
61 |
62 | /* Convert the Curve25519 public key into an Ed25519 public key. In
63 | particular, convert Curve25519's "montgomery" x-coordinate (u) into an
64 | Ed25519 "edwards" y-coordinate:
65 |
66 | y = (u - 1) / (u + 1)
67 |
68 | NOTE: u=-1 is converted to y=0 since fe_invert is mod-exp
69 |
70 | Then move the sign bit into the pubkey from the signature.
71 | */
72 | fe_frombytes(u, curve25519_pubkey);
73 | fe_montx_to_edy(y, u);
74 | fe_tobytes(ed_pubkey, y);
75 |
76 | /* Copy the sign bit, and remove it from signature */
77 | ed_pubkey[31] &= 0x7F; /* bit should be zero already, but just in case */
78 | ed_pubkey[31] |= (signature[63] & 0x80);
79 | memmove(verifybuf, signature, 64);
80 | verifybuf[63] &= 0x7F;
81 |
82 | memmove(verifybuf+64, msg, msg_len);
83 |
84 | /* Then perform a normal Ed25519 verification, return 0 on success */
85 | /* The below call has a strange API: */
86 | /* verifybuf = R || S || message */
87 | /* verifybuf2 = internal to next call gets a copy of verifybuf, S gets
88 | replaced with pubkey for hashing */
89 | result = crypto_sign_open_modified(verifybuf2, verifybuf, 64 + msg_len, ed_pubkey);
90 |
91 | err:
92 |
93 | if (verifybuf != NULL) {
94 | free(verifybuf);
95 | }
96 |
97 | if (verifybuf2 != NULL) {
98 | free(verifybuf2);
99 | }
100 |
101 | return result;
102 | }
103 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/fe_tobytes.c:
--------------------------------------------------------------------------------
1 | #include "fe.h"
2 |
3 | /*
4 | Preconditions:
5 | |h| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc.
6 |
7 | Write p=2^255-19; q=floor(h/p).
8 | Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))).
9 |
10 | Proof:
11 | Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4.
12 | Also have |h-2^230 h9|<2^231 so |19 2^(-255)(h-2^230 h9)|<1/4.
13 |
14 | Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9).
15 | Then 0> 25;
53 | q = (h0 + q) >> 26;
54 | q = (h1 + q) >> 25;
55 | q = (h2 + q) >> 26;
56 | q = (h3 + q) >> 25;
57 | q = (h4 + q) >> 26;
58 | q = (h5 + q) >> 25;
59 | q = (h6 + q) >> 26;
60 | q = (h7 + q) >> 25;
61 | q = (h8 + q) >> 26;
62 | q = (h9 + q) >> 25;
63 |
64 | /* Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. */
65 | h0 += 19 * q;
66 | /* Goal: Output h-2^255 q, which is between 0 and 2^255-20. */
67 |
68 | carry0 = h0 >> 26; h1 += carry0; h0 -= carry0 << 26;
69 | carry1 = h1 >> 25; h2 += carry1; h1 -= carry1 << 25;
70 | carry2 = h2 >> 26; h3 += carry2; h2 -= carry2 << 26;
71 | carry3 = h3 >> 25; h4 += carry3; h3 -= carry3 << 25;
72 | carry4 = h4 >> 26; h5 += carry4; h4 -= carry4 << 26;
73 | carry5 = h5 >> 25; h6 += carry5; h5 -= carry5 << 25;
74 | carry6 = h6 >> 26; h7 += carry6; h6 -= carry6 << 26;
75 | carry7 = h7 >> 25; h8 += carry7; h7 -= carry7 << 25;
76 | carry8 = h8 >> 26; h9 += carry8; h8 -= carry8 << 26;
77 | carry9 = h9 >> 25; h9 -= carry9 << 25;
78 | /* h10 = carry9 */
79 |
80 | /*
81 | Goal: Output h0+...+2^255 h10-2^255 q, which is between 0 and 2^255-20.
82 | Have h0+...+2^230 h9 between 0 and 2^255-1;
83 | evidently 2^255 h10-2^255 q = 0.
84 | Goal: Output h0+...+2^230 h9.
85 | */
86 |
87 | s[0] = h0 >> 0;
88 | s[1] = h0 >> 8;
89 | s[2] = h0 >> 16;
90 | s[3] = (h0 >> 24) | (h1 << 2);
91 | s[4] = h1 >> 6;
92 | s[5] = h1 >> 14;
93 | s[6] = (h1 >> 22) | (h2 << 3);
94 | s[7] = h2 >> 5;
95 | s[8] = h2 >> 13;
96 | s[9] = (h2 >> 21) | (h3 << 5);
97 | s[10] = h3 >> 3;
98 | s[11] = h3 >> 11;
99 | s[12] = (h3 >> 19) | (h4 << 6);
100 | s[13] = h4 >> 2;
101 | s[14] = h4 >> 10;
102 | s[15] = h4 >> 18;
103 | s[16] = h5 >> 0;
104 | s[17] = h5 >> 8;
105 | s[18] = h5 >> 16;
106 | s[19] = (h5 >> 24) | (h6 << 1);
107 | s[20] = h6 >> 7;
108 | s[21] = h6 >> 15;
109 | s[22] = (h6 >> 23) | (h7 << 3);
110 | s[23] = h7 >> 5;
111 | s[24] = h7 >> 13;
112 | s[25] = (h7 >> 21) | (h8 << 4);
113 | s[26] = h8 >> 4;
114 | s[27] = h8 >> 12;
115 | s[28] = (h8 >> 20) | (h9 << 6);
116 | s[29] = h9 >> 2;
117 | s[30] = h9 >> 10;
118 | s[31] = h9 >> 18;
119 | }
120 |
--------------------------------------------------------------------------------
/libsignal-protocol-swiftTests/FingerprintTests.swift:
--------------------------------------------------------------------------------
1 | //
2 | // FingerprintTests.swift
3 | // libsignal-protocol-swiftTests
4 | //
5 | // Created by User on 19.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import XCTest
10 | import SignalProtocol
11 |
12 | class FingerprintTests: XCTestCase {
13 |
14 | func testFingerprint() {
15 |
16 | let alice = try! Signal.generateIdentityKeyPair().publicKey
17 | let bob = try! Signal.generateIdentityKeyPair().publicKey
18 |
19 | let aliceAddress = "+14152222222"
20 | let bobAddress = "+14153333333"
21 |
22 | let iterations = 1024
23 |
24 | let aliceFingerprint: Fingerprint
25 | do {
26 | aliceFingerprint = try Fingerprint(
27 | iterations: iterations,
28 | localIdentifier: aliceAddress, localIdentity: alice,
29 | remoteIdentifier: bobAddress, remoteIdentity: bob)
30 | } catch {
31 | XCTFail("Could not create fingerprint for alice: \(error)")
32 | return
33 | }
34 |
35 | let bobFingerprint: Fingerprint
36 | do {
37 | bobFingerprint = try Fingerprint(
38 | iterations: iterations,
39 | localIdentifier: bobAddress, localIdentity: bob,
40 | remoteIdentifier: aliceAddress, remoteIdentity: alice)
41 | } catch {
42 | XCTFail("Could not create fingerprint for bob: \(error)")
43 | return
44 | }
45 |
46 | do {
47 | let equal = try aliceFingerprint.matches(scannable: bobFingerprint)
48 | XCTAssert(equal, "Fingerprints don't match")
49 | } catch {
50 | XCTFail("Could not match fingerprints: \(error)")
51 | return
52 | }
53 | }
54 |
55 | func testFingerprintLists() {
56 | let aliceKeys = [try! Signal.generateIdentityKeyPair().publicKey,
57 | try! Signal.generateIdentityKeyPair().publicKey,
58 | try! Signal.generateIdentityKeyPair().publicKey]
59 |
60 | let bobKeys = [try! Signal.generateIdentityKeyPair().publicKey,
61 | try! Signal.generateIdentityKeyPair().publicKey,
62 | try! Signal.generateIdentityKeyPair().publicKey]
63 |
64 | let aliceAddress = "+14152222222"
65 | let bobAddress = "+14153333333"
66 |
67 | let iterations = 1024
68 |
69 | let aliceFingerprint: Fingerprint
70 | do {
71 | aliceFingerprint = try Fingerprint(
72 | iterations: iterations,
73 | localIdentifier: aliceAddress, localIdentityList: aliceKeys,
74 | remoteIdentifier: bobAddress, remoteIdentityList: bobKeys)
75 | } catch {
76 | XCTFail("Could not create fingerprint for alice: \(error)")
77 | return
78 | }
79 |
80 | let bobFingerprint: Fingerprint
81 | do {
82 | bobFingerprint = try Fingerprint(
83 | iterations: iterations,
84 | localIdentifier: bobAddress, localIdentityList: bobKeys,
85 | remoteIdentifier: aliceAddress, remoteIdentityList: aliceKeys)
86 | } catch {
87 | XCTFail("Could not create fingerprint for bob: \(error)")
88 | return
89 | }
90 |
91 | do {
92 | let equal = try aliceFingerprint.matches(scannable: bobFingerprint)
93 | XCTAssert(equal, "Fingerprints don't match")
94 | let equal2 = try bobFingerprint.matches(scannable: aliceFingerprint)
95 | XCTAssert(equal2, "Fingerprints don't match")
96 | } catch {
97 | XCTFail("Could not match fingerprints: \(error)")
98 | return
99 | }
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/curve25519/ed25519/additions/ge_scalarmult.c:
--------------------------------------------------------------------------------
1 | #include "crypto_uint32.h"
2 | #include "ge.h"
3 | #include "crypto_additions.h"
4 |
5 | static unsigned char equal(signed char b,signed char c)
6 | {
7 | unsigned char ub = b;
8 | unsigned char uc = c;
9 | unsigned char x = ub ^ uc; /* 0: yes; 1..255: no */
10 | crypto_uint32 y = x; /* 0: yes; 1..255: no */
11 | y -= 1; /* 4294967295: yes; 0..254: no */
12 | y >>= 31; /* 1: yes; 0: no */
13 | return y;
14 | }
15 |
16 | static unsigned char negative(signed char b)
17 | {
18 | unsigned long long x = b; /* 18446744073709551361..18446744073709551615: yes; 0..255: no */
19 | x >>= 63; /* 1: yes; 0: no */
20 | return x;
21 | }
22 |
23 | static void cmov(ge_cached *t,const ge_cached *u,unsigned char b)
24 | {
25 | fe_cmov(t->YplusX,u->YplusX,b);
26 | fe_cmov(t->YminusX,u->YminusX,b);
27 | fe_cmov(t->Z,u->Z,b);
28 | fe_cmov(t->T2d,u->T2d,b);
29 | }
30 |
31 | static void select(ge_cached *t,const ge_cached *pre, signed char b)
32 | {
33 | ge_cached minust;
34 | unsigned char bnegative = negative(b);
35 | unsigned char babs = b - (((-bnegative) & b) << 1);
36 |
37 | fe_1(t->YplusX);
38 | fe_1(t->YminusX);
39 | fe_1(t->Z);
40 | fe_0(t->T2d);
41 |
42 | cmov(t,pre+0,equal(babs,1));
43 | cmov(t,pre+1,equal(babs,2));
44 | cmov(t,pre+2,equal(babs,3));
45 | cmov(t,pre+3,equal(babs,4));
46 | cmov(t,pre+4,equal(babs,5));
47 | cmov(t,pre+5,equal(babs,6));
48 | cmov(t,pre+6,equal(babs,7));
49 | cmov(t,pre+7,equal(babs,8));
50 | fe_copy(minust.YplusX,t->YminusX);
51 | fe_copy(minust.YminusX,t->YplusX);
52 | fe_copy(minust.Z,t->Z);
53 | fe_neg(minust.T2d,t->T2d);
54 | cmov(t,&minust,bnegative);
55 | }
56 |
57 | /*
58 | h = a * B
59 | where a = a[0]+256*a[1]+...+256^31 a[31]
60 | B is the Ed25519 base point (x,4/5) with x positive.
61 |
62 | Preconditions:
63 | a[31] <= 127
64 | */
65 |
66 | void ge_scalarmult(ge_p3 *h, const unsigned char *a, const ge_p3 *A)
67 | {
68 | signed char e[64];
69 | signed char carry;
70 | ge_p1p1 r;
71 | ge_p2 s;
72 | ge_p3 t0, t1, t2;
73 | ge_cached t, pre[8];
74 | int i;
75 |
76 | for (i = 0;i < 32;++i) {
77 | e[2 * i + 0] = (a[i] >> 0) & 15;
78 | e[2 * i + 1] = (a[i] >> 4) & 15;
79 | }
80 | /* each e[i] is between 0 and 15 */
81 | /* e[63] is between 0 and 7 */
82 |
83 | carry = 0;
84 | for (i = 0;i < 63;++i) {
85 | e[i] += carry;
86 | carry = e[i] + 8;
87 | carry >>= 4;
88 | e[i] -= carry << 4;
89 | }
90 | e[63] += carry;
91 | /* each e[i] is between -8 and 8 */
92 |
93 | // Precomputation:
94 | ge_p3_to_cached(pre+0, A); // A
95 |
96 | ge_p3_dbl(&r, A);
97 | ge_p1p1_to_p3(&t0, &r);
98 | ge_p3_to_cached(pre+1, &t0); // 2A
99 |
100 | ge_add(&r, A, pre+1);
101 | ge_p1p1_to_p3(&t1, &r);
102 | ge_p3_to_cached(pre+2, &t1); // 3A
103 |
104 | ge_p3_dbl(&r, &t0);
105 | ge_p1p1_to_p3(&t0, &r);
106 | ge_p3_to_cached(pre+3, &t0); // 4A
107 |
108 | ge_add(&r, A, pre+3);
109 | ge_p1p1_to_p3(&t2, &r);
110 | ge_p3_to_cached(pre+4, &t2); // 5A
111 |
112 | ge_p3_dbl(&r, &t1);
113 | ge_p1p1_to_p3(&t1, &r);
114 | ge_p3_to_cached(pre+5, &t1); // 6A
115 |
116 | ge_add(&r, A, pre+5);
117 | ge_p1p1_to_p3(&t1, &r);
118 | ge_p3_to_cached(pre+6, &t1); // 7A
119 |
120 | ge_p3_dbl(&r, &t0);
121 | ge_p1p1_to_p3(&t0, &r);
122 | ge_p3_to_cached(pre+7, &t0); // 8A
123 |
124 | ge_p3_0(h);
125 |
126 | for (i = 63;i > 0; i--) {
127 | select(&t,pre,e[i]);
128 | ge_add(&r, h, &t);
129 | ge_p1p1_to_p2(&s,&r);
130 |
131 | ge_p2_dbl(&r,&s); ge_p1p1_to_p2(&s,&r);
132 | ge_p2_dbl(&r,&s); ge_p1p1_to_p2(&s,&r);
133 | ge_p2_dbl(&r,&s); ge_p1p1_to_p2(&s,&r);
134 | ge_p2_dbl(&r,&s); ge_p1p1_to_p3(h,&r);
135 |
136 | }
137 | select(&t,pre,e[0]);
138 | ge_add(&r, h, &t);
139 | ge_p1p1_to_p3(h,&r);
140 | }
141 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/signal_protocol_internal.h:
--------------------------------------------------------------------------------
1 | #ifndef SIGNAL_PROTOCOL_INTERNAL_H
2 | #define SIGNAL_PROTOCOL_INTERNAL_H
3 |
4 | #include
5 | #include "LocalStorageProtocol.pb-c.h"
6 | #include "signal_protocol.h"
7 |
8 | struct signal_type_base {
9 | unsigned int ref_count;
10 | void (*destroy)(signal_type_base *instance);
11 | };
12 |
13 | void signal_type_init(signal_type_base *instance,
14 | void (*destroy_func)(signal_type_base *instance));
15 |
16 | #define SIGNAL_INIT(instance, destroy_func) signal_type_init((signal_type_base *)instance, destroy_func)
17 |
18 | struct signal_buffer {
19 | size_t len;
20 | uint8_t data[];
21 | };
22 |
23 | struct signal_context {
24 | signal_crypto_provider crypto_provider;
25 | void (*lock)(void *user_data);
26 | void (*unlock)(void *user_data);
27 | void (*log)(int level, const char *message, size_t len, void *user_data);
28 | void *user_data;
29 | };
30 |
31 | int signal_crypto_random(signal_context *context, uint8_t *data, size_t len);
32 |
33 | int signal_hmac_sha256_init(signal_context *context, void **hmac_context, const uint8_t *key, size_t key_len);
34 | int signal_hmac_sha256_update(signal_context *context, void *hmac_context, const uint8_t *data, size_t data_len);
35 | int signal_hmac_sha256_final(signal_context *context, void *hmac_context, signal_buffer **output);
36 | void signal_hmac_sha256_cleanup(signal_context *context, void *hmac_context);
37 |
38 | int signal_sha512_digest_init(signal_context *context, void **digest_context);
39 | int signal_sha512_digest_update(signal_context *context, void *digest_context, const uint8_t *data, size_t data_len);
40 | int signal_sha512_digest_final(signal_context *context, void *digest_context, signal_buffer **output);
41 | void signal_sha512_digest_cleanup(signal_context *context, void *digest_context);
42 |
43 |
44 | int signal_encrypt(signal_context *context,
45 | signal_buffer **output,
46 | int cipher,
47 | const uint8_t *key, size_t key_len,
48 | const uint8_t *iv, size_t iv_len,
49 | const uint8_t *plaintext, size_t plaintext_len);
50 |
51 | int signal_decrypt(signal_context *context,
52 | signal_buffer **output,
53 | int cipher,
54 | const uint8_t *key, size_t key_len,
55 | const uint8_t *iv, size_t iv_len,
56 | const uint8_t *ciphertext, size_t ciphertext_len);
57 |
58 | void signal_lock(signal_context *context);
59 | void signal_unlock(signal_context *context);
60 | void signal_log(signal_context *context, int level, const char *format, ...);
61 | void signal_explicit_bzero(void *v, size_t n);
62 | int signal_constant_memcmp(const void *s1, const void *s2, size_t n);
63 |
64 | /*------------------------------------------------------------------------*/
65 |
66 | /*
67 | * Functions used for internal protocol buffers serialization support.
68 | */
69 |
70 | int ec_public_key_serialize_protobuf(ProtobufCBinaryData *buffer, const ec_public_key *key);
71 | int ec_private_key_serialize_protobuf(ProtobufCBinaryData *buffer, const ec_private_key *key);
72 |
73 | int ratchet_chain_key_get_key_protobuf(const ratchet_chain_key *chain_key, ProtobufCBinaryData *buffer);
74 | int ratchet_root_key_get_key_protobuf(const ratchet_root_key *root_key, ProtobufCBinaryData *buffer);
75 |
76 | int session_state_serialize_prepare(session_state *state, Textsecure__SessionStructure *session_structure);
77 | void session_state_serialize_prepare_free(Textsecure__SessionStructure *session_structure);
78 | int session_state_deserialize_protobuf(session_state **state, Textsecure__SessionStructure *session_structure, signal_context *global_context);
79 |
80 | int sender_key_state_serialize_prepare(sender_key_state *state, Textsecure__SenderKeyStateStructure *state_structure);
81 | void sender_key_state_serialize_prepare_free(Textsecure__SenderKeyStateStructure *state_structure);
82 | int sender_key_state_deserialize_protobuf(sender_key_state **state, Textsecure__SenderKeyStateStructure *state_structure, signal_context *global_context);
83 |
84 | void signal_protocol_str_serialize_protobuf(ProtobufCBinaryData *buffer, const char *str);
85 | char *signal_protocol_str_deserialize_protobuf(ProtobufCBinaryData *buffer);
86 |
87 | #endif /* SIGNAL_PROTOCOL_INTERNAL_H */
88 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/Stores/SignalStore.swift:
--------------------------------------------------------------------------------
1 | //
2 | // SignalStore.swift
3 | // libsignal-protocol-swift
4 | //
5 | // Created by User on 15.02.18.
6 | // Copyright © 2018 User. All rights reserved.
7 | //
8 |
9 | import Foundation
10 | import SignalModule
11 |
12 | /**
13 | A `SignalStore` provides access to all required data stores for a client.
14 | */
15 | public final class SignalStore {
16 |
17 | /// Count of all active stores
18 | private static var instanceCount = 0
19 |
20 | /// Pointer to store, used to identify delegate in callbacks
21 | private let instanceId: UnsafeMutablePointer
22 |
23 | /// The store context pointer of the instance
24 | let storeContext: OpaquePointer
25 |
26 | /// The delegate that handles the identity key store operations
27 | public let identityKeyStore: IdentityKeyStore
28 |
29 | /// The delegate that handles the pre key store operations
30 | public let preKeyStore: PreKeyStore
31 |
32 | /// The delegate that handles the session store operations
33 | public let sessionStore: SessionStore
34 |
35 | /// The delegate that handles the signed pre key store operations
36 | public let signedPreKeyStore: SignedPreKeyStore
37 |
38 | /// The delegate that handles the sender key store operations, optional
39 | public let senderKeyStore: SenderKeyStore?
40 |
41 | /**
42 | Create a `SignalStore` with the necessary delegates.
43 | - parameter identityKeyStore: The identity key store for this instance
44 | - parameter preKeyStore: The pre key store for this instance
45 | - parameter sessionStore: The session store for this instance
46 | - parameter signedPreKeyStore: The signed pre key store for this instance
47 | - parameter senderKeyStore: The (optional) sender key store for this instance, only needed for group messages
48 | - throws: Errors of type `SignalError`
49 | */
50 | public init(identityKeyStore: IdentityKeyStore,
51 | preKeyStore: PreKeyStore,
52 | sessionStore: SessionStore,
53 | signedPreKeyStore: SignedPreKeyStore,
54 | senderKeyStore: SenderKeyStore?) throws {
55 |
56 | var store: OpaquePointer? = nil
57 | let result = withUnsafeMutablePointer(to: &store) {
58 | signal_protocol_store_context_create($0, Signal.context)
59 | }
60 | guard result == 0 else { throw SignalError(value: result) }
61 |
62 | self.instanceId = UnsafeMutablePointer.allocate(capacity: 1)
63 | self.instanceId.pointee = SignalStore.instanceCount
64 | SignalStore.instanceCount += 1
65 |
66 | self.storeContext = store!
67 | self.identityKeyStore = identityKeyStore
68 | self.preKeyStore = preKeyStore
69 | self.senderKeyStore = senderKeyStore
70 | self.sessionStore = sessionStore
71 | self.signedPreKeyStore = signedPreKeyStore
72 |
73 | try registerDelegates()
74 | }
75 |
76 | /// Add delegates to wrapper classes
77 | private func registerDelegates() throws {
78 | try IdentityKeyStoreWrapper.setStore(in: storeContext, delegate: identityKeyStore, userData: instanceId)
79 | try PreKeyStoreWrapper.setStore(in: storeContext, delegate: preKeyStore, userData: instanceId)
80 | try SessionStoreWrapper.setStore(in: storeContext, delegate: sessionStore, userData: instanceId)
81 | try SignedPreKeyStoreWrapper.setStore(in: storeContext, delegate: signedPreKeyStore, userData: instanceId)
82 | if senderKeyStore != nil {
83 | try SenderKeyStoreWrapper.setStore(in: storeContext, delegate: senderKeyStore!, userData: instanceId)
84 | }
85 | }
86 |
87 | /// Remove delegates from wrapper classes
88 | private func unregisterDelegates() {
89 | let id = instanceId.pointee
90 |
91 | IdentityKeyStoreWrapper.removeDelegate(for: id)
92 | PreKeyStoreWrapper.removeDelegate(for: id)
93 | SenderKeyStoreWrapper.removeDelegate(for: id)
94 | SessionStoreWrapper.removeDelegate(for: id)
95 | SignedPreKeyStoreWrapper.removeDelegate(for: id)
96 | }
97 |
98 | deinit {
99 | unregisterDelegates()
100 | self.instanceId.deallocate()
101 | signal_protocol_store_context_destroy(storeContext)
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/signal_protocol_types.h:
--------------------------------------------------------------------------------
1 | #ifndef SIGNAL_PROTOCOL_TYPES_H
2 | #define SIGNAL_PROTOCOL_TYPES_H
3 |
4 | #include
5 | #include
6 |
7 | #ifndef _WINDOWS
8 | #include
9 | #else
10 | #include
11 | typedef SSIZE_T ssize_t;
12 | #endif
13 |
14 | #ifdef __cplusplus
15 | extern "C" {
16 | #endif
17 |
18 | /*
19 | * Base library types
20 | */
21 | typedef struct signal_type_base signal_type_base;
22 | typedef struct signal_buffer signal_buffer;
23 | typedef struct signal_buffer_list signal_buffer_list;
24 | typedef struct signal_int_list signal_int_list;
25 |
26 | /*
27 | * Global context for the Signal Protocol library
28 | */
29 | typedef struct signal_context signal_context;
30 |
31 | /*
32 | * Context for the Signal Protocol data store implementation
33 | */
34 | typedef struct signal_protocol_store_context signal_protocol_store_context;
35 |
36 | /*
37 | * Address of an Signal Protocol message recipient
38 | */
39 | typedef struct signal_protocol_address {
40 | const char *name;
41 | size_t name_len;
42 | int32_t device_id;
43 | } signal_protocol_address;
44 |
45 | /*
46 | * A representation of a (group + sender + device) tuple
47 | */
48 | typedef struct signal_protocol_sender_key_name {
49 | const char *group_id;
50 | size_t group_id_len;
51 | signal_protocol_address sender;
52 | } signal_protocol_sender_key_name;
53 |
54 | /*
55 | * Curve key types
56 | */
57 | typedef struct ec_public_key ec_public_key;
58 | typedef struct ec_private_key ec_private_key;
59 | typedef struct ec_key_pair ec_key_pair;
60 | typedef struct ec_public_key_list ec_public_key_list;
61 |
62 | /*
63 | * HKDF types
64 | */
65 | typedef struct hkdf_context hkdf_context;
66 |
67 | /*
68 | * Key helper types
69 | */
70 | typedef struct signal_protocol_key_helper_pre_key_list_node signal_protocol_key_helper_pre_key_list_node;
71 |
72 | /*
73 | * Protocol types
74 | */
75 | typedef struct ciphertext_message ciphertext_message;
76 | typedef struct signal_message signal_message;
77 | typedef struct pre_key_signal_message pre_key_signal_message;
78 | typedef struct sender_key_message sender_key_message;
79 | typedef struct sender_key_distribution_message sender_key_distribution_message;
80 |
81 | /*
82 | * Ratchet types
83 | */
84 | #define RATCHET_CIPHER_KEY_LENGTH 32
85 | #define RATCHET_MAC_KEY_LENGTH 32
86 | #define RATCHET_IV_LENGTH 16
87 |
88 | typedef struct ratchet_chain_key ratchet_chain_key;
89 | typedef struct ratchet_root_key ratchet_root_key;
90 | typedef struct ratchet_identity_key_pair ratchet_identity_key_pair;
91 |
92 | typedef struct ratchet_message_keys {
93 | uint8_t cipher_key[RATCHET_CIPHER_KEY_LENGTH];
94 | uint8_t mac_key[RATCHET_MAC_KEY_LENGTH];
95 | uint8_t iv[RATCHET_IV_LENGTH];
96 | uint32_t counter;
97 | } ratchet_message_keys;
98 |
99 | /*
100 | * Session types
101 | */
102 | typedef struct session_pre_key session_pre_key;
103 | typedef struct session_signed_pre_key session_signed_pre_key;
104 | typedef struct session_pre_key_bundle session_pre_key_bundle;
105 | typedef struct session_builder session_builder;
106 | typedef struct session_record session_record;
107 | typedef struct session_record_state_node session_record_state_node;
108 | typedef struct session_state session_state;
109 | typedef struct session_cipher session_cipher;
110 |
111 | /*
112 | * Group types
113 | */
114 | typedef struct sender_message_key sender_message_key;
115 | typedef struct sender_chain_key sender_chain_key;
116 | typedef struct sender_key_state sender_key_state;
117 | typedef struct sender_key_record sender_key_record;
118 | typedef struct group_session_builder group_session_builder;
119 | typedef struct group_cipher group_cipher;
120 |
121 | /*
122 | * Fingerprint types
123 | */
124 | typedef struct fingerprint fingerprint;
125 | typedef struct displayable_fingerprint displayable_fingerprint;
126 | typedef struct scannable_fingerprint scannable_fingerprint;
127 | typedef struct fingerprint_generator fingerprint_generator;
128 |
129 | /*
130 | * Device consistency types
131 | */
132 | typedef struct device_consistency_signature device_consistency_signature;
133 | typedef struct device_consistency_commitment device_consistency_commitment;
134 | typedef struct device_consistency_message device_consistency_message;
135 | typedef struct device_consistency_signature_list device_consistency_signature_list;
136 |
137 | #ifdef __cplusplus
138 | }
139 | #endif
140 |
141 | #endif /* SIGNAL_PROTOCOL_TYPES_H */
142 |
--------------------------------------------------------------------------------
/libsignal-protocol-swift/libsignal-protocol-c/group_cipher.h:
--------------------------------------------------------------------------------
1 | #ifndef GROUP_CIPHER_H
2 | #define GROUP_CIPHER_H
3 |
4 | #include
5 | #include
6 | #include "signal_protocol_types.h"
7 |
8 | #ifdef __cplusplus
9 | extern "C" {
10 | #endif
11 |
12 | /*
13 | * The main entry point for Signal Protocol group encrypt/decrypt operations.
14 | *
15 | * Once a session has been established with group_session_builder and a
16 | * sender_key_distribution_message has been distributed to each member of
17 | * the group, this class can be used for all subsequent encrypt/decrypt
18 | * operations within that session (i.e. until group membership changes).
19 | */
20 |
21 | /**
22 | * Construct a group cipher for encrypt/decrypt operations.
23 | *
24 | * The store and global contexts must remain valid for the lifetime of the
25 | * group cipher.
26 | *
27 | * When finished, free the returned instance by calling group_cipher_free().
28 | *
29 | * @param cipher set to a freshly allocated group cipher instance
30 | * @param store the signal_protocol_store_context to store all state information in
31 | * @param sender_key_id the sender that messages will be encrypted to or decrypted from
32 | * @param global_context the global library context
33 | * @return 0 on success, or negative on failure
34 | */
35 | int group_cipher_create(group_cipher **cipher,
36 | signal_protocol_store_context *store, const signal_protocol_sender_key_name *sender_key_id,
37 | signal_context *global_context);
38 |
39 | /**
40 | * Set the optional user data pointer for the group cipher.
41 | *
42 | * This is to give callback functions a way of accessing app specific
43 | * context information for this cipher.
44 | */
45 | void group_cipher_set_user_data(group_cipher *cipher, void *user_data);
46 |
47 | /**
48 | * Get the optional user data pointer for the group cipher.
49 | *
50 | * This is to give callback functions a way of accessing app specific
51 | * context information for this cipher.
52 | */
53 | void *group_cipher_get_user_data(group_cipher *cipher);
54 |
55 | /**
56 | * Set the callback function that is called during the decrypt process.
57 | *
58 | * The callback function is called from within group_cipher_decrypt() after
59 | * decryption is complete but before the updated session state has been
60 | * committed to the session store. If the callback function returns a
61 | * negative value, then the decrypt function will immediately fail with
62 | * an error.
63 | *
64 | * This a callback allows some implementations to store the committed plaintext
65 | * to their local message store first, in case they are concerned with a crash
66 | * or write error happening between the time the session state is updated but
67 | * before they're able to successfully store the plaintext to disk.
68 | *
69 | * @param callback the callback function to set
70 | */
71 | void group_cipher_set_decryption_callback(group_cipher *cipher,
72 | int (*callback)(group_cipher *cipher, signal_buffer *plaintext, void *decrypt_context));
73 |
74 | /**
75 | * Encrypt a message.
76 | *
77 | * @param padded_plaintext The plaintext message bytes, optionally padded to a constant multiple.
78 | * @param padded_plaintext_len The length of the data pointed to by padded_message
79 | * @param encrypted_message Set to a ciphertext message encrypted to the group+sender+device tuple.
80 | *
81 | * @retval SG_SUCCESS Success
82 | * @retval SG_ERR_NO_SESSION if there is no established session for this contact.
83 | * @retval SG_ERR_INVALID_KEY if there is no valid private key for this session.
84 | */
85 | int group_cipher_encrypt(group_cipher *cipher,
86 | const uint8_t *padded_plaintext, size_t padded_plaintext_len,
87 | ciphertext_message **encrypted_message);
88 |
89 | /**
90 | * Decrypt a message.
91 | *
92 | * @param ciphertext The sender_key_message to decrypt.
93 | * @param decrypt_context Optional context pointer associated with the
94 | * ciphertext, which is passed to the decryption callback function
95 | * @param plaintext Set to a newly allocated buffer containing the plaintext.
96 | *
97 | * @retval SG_SUCCESS Success
98 | * @retval SG_ERR_INVALID_MESSAGE if the input is not valid ciphertext.
99 | * @retval SG_ERR_DUPLICATE_MESSAGE if the input is a message that has already been received.
100 | * @retval SG_ERR_LEGACY_MESSAGE if the input is a message formatted by a protocol version that
101 | * is no longer supported.
102 | * @retval SG_ERR_NO_SESSION if there is no established session for this contact.
103 | */
104 | int group_cipher_decrypt(group_cipher *cipher,
105 | sender_key_message *ciphertext, void *decrypt_context,
106 | signal_buffer **plaintext);
107 |
108 | void group_cipher_free(group_cipher *cipher);
109 |
110 | #ifdef __cplusplus
111 | }
112 | #endif
113 |
114 | #endif /* GROUP_CIPHER_H */
115 |
--------------------------------------------------------------------------------