Esempio n. 1
0
        private byte[] getMac(uint messageVersion,
                              IdentityKey senderIdentityKey,
                              IdentityKey receiverIdentityKey,
                              byte[] macKey, byte[] serialized)
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                if (messageVersion >= 3)
                {
                    byte[] sik = senderIdentityKey.getPublicKey().serialize();
                    stream.Write(sik, 0, sik.Length);
                    byte[] rik = receiverIdentityKey.getPublicKey().serialize();
                    stream.Write(rik, 0, rik.Length);
                }

                stream.Write(serialized, 0, serialized.Length);
                byte[] fullMac = Sign.sha256sum(macKey, stream.ToArray());
                return(ByteUtil.trim(fullMac, MAC_LENGTH));
            }
            catch (/*NoSuchAlgorithmException | java.security.InvalidKey*/ Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Esempio n. 2
0
        private string getDisplayStringFor(string stableIdentifier, IdentityKey identityKey)
        {
            try
            {
                IHashAlgorithmProvider digest = HashAlgorithmProvider.OpenAlgorithm(PCLCrypto.HashAlgorithm.Sha512);

                byte[] publicKey = identityKey.getPublicKey().serialize();
                byte[] hash      = ByteUtil.combine(ByteUtil.shortToByteArray(VERSION),
                                                    publicKey, Encoding.UTF8.GetBytes(stableIdentifier));

                for (int i = 0; i < iterations; i++)
                {
                    hash = digest.HashData(ByteUtil.combine(new byte[][] { hash, publicKey }));
                }

                return(getEncodedChunk(hash, 0) +
                       getEncodedChunk(hash, 5) +
                       getEncodedChunk(hash, 10) +
                       getEncodedChunk(hash, 15) +
                       getEncodedChunk(hash, 20) +
                       getEncodedChunk(hash, 25));
            }
            catch (Exception e)
            {
                Debug.Assert(false, e.Message);
                throw e;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Generates the display fingerprint for the given OMEMO identity public key.
        /// </summary>
        /// <param name="key">The OMEMO identity public key.</param>
        /// <param name="twoLines">Split the fingerprint into two lines.</param>
        /// <returns>A hex string representing the given OMEMO identity public key. Split up in blocks of 8 characters separated by a whitespace.</returns>
        public static string generateOmemoFingerprint(IdentityKey key, bool twoLines)
        {
            byte[] keyRaw      = getRawFromECPublicKey(key.getPublicKey());
            string fingerprint = byteArrayToHexString(keyRaw);

            fingerprint = Regex.Replace(fingerprint, ".{8}", "$0 ").TrimEnd();
            if (twoLines)
            {
                fingerprint = Regex.Replace(fingerprint, ".{36}", "$0\n").TrimEnd();
            }
            return(fingerprint);
        }
        public DeviceConsistencyMessage(DeviceConsistencyCommitment commitment, byte[] serialized, IdentityKey identityKey)
        {
            try
            {
                DeviceConsistencyCodeMessage message = DeviceConsistencyCodeMessage.Parser.ParseFrom(serialized);
                byte[] vrfOutputBytes = Curve.verifyVrfSignature(identityKey.getPublicKey(), commitment.toByteArray(), message.Signature.ToByteArray());

                this.generation = (int)message.Generation;
                this.signature  = new DeviceConsistencySignature(message.Signature.ToByteArray(), vrfOutputBytes);
                this.serialized = serialized;
            }
            catch (InvalidProtocolBufferException e)
            {
                throw new InvalidMessageException(e);
            }
            catch (InvalidKeyException e)
            {
                throw new InvalidMessageException(e);
            }
            catch (VrfSignatureVerificationFailedException e)
            {
                throw new InvalidMessageException(e);
            }
        }
        public Models.Message[] GetMessages(ISharedPreferences sharedPref, User SelectedFriend, SessionStore sessionStore,
                                            PreKeyStore preKeyStore, SignedPreKeyStore signedPreKeyStore, IdentityKeyStore identityStore, SignalProtocolAddress SelectedFriendAddress)
        {
            // send the server the user name
            // server side does the selection and return the messages and store it in a message array.
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "getMessage";

            //Login_Request has two properties:username and password
            Login_Request myLogin_Request = new Login_Request();

            Models.Message recieveMessage = new Models.Message();

            //get the login username from previow login page.
            recieveMessage.MessageReceiverRegisID = Convert.ToUInt32(sharedPref.GetString("RegistrationId", string.Empty));
            recieveMessage.MessageSenderRegisID   = SelectedFriend.RegisterationID;
            myLogin_Request.message = recieveMessage;
            UserID = myLogin_Request.RegistrationID;


            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response2 r = JsonConvert.DeserializeObject <API_Response2>(response);

            // check response
            if (r != null)
            {
                if (!r.IsError && !string.IsNullOrEmpty(r.MessageText))
                {
                    SessionCipher sessionCipher = new SessionCipher(sessionStore, preKeyStore, signedPreKeyStore, identityStore, SelectedFriendAddress);
                    byte[]        decipherMessage;
                    if (!sessionStore.ContainsSession(SelectedFriendAddress))
                    {
                        decipherMessage = sessionCipher.decrypt(new PreKeySignalMessage((JsonConvert.DeserializeObject <byte[]>(r.MessageText))));
                    }
                    else
                    {
                        decipherMessage = sessionCipher.decrypt(new SignalMessage((JsonConvert.DeserializeObject <byte[]>(r.MessageText))));
                    }
                    string checkMessage = Encoding.UTF8.GetString(decipherMessage);

                    SelectedFriend.SelectedUserMessages.Add(new Models.Message
                    {
                        MessageID              = r.MessageID,
                        MessageSenderRegisID   = r.MessageSenderRegisID,
                        MessageReceiverRegisID = r.MessageReceiverRegisID,
                        MessageText            = checkMessage,
                        MessageTimestamp       = r.MessageTimestamp
                    });

                    return(SelectedFriend.SelectedUserMessages.ToArray());
                }
                else
                {
                    //if login fails, pop up an alert message. Wrong username or password or a new user
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    if (!string.IsNullOrEmpty(r.ErrorMessage))
                    {
                        dialogBuilder.SetMessage(r.ErrorMessage);
                    }
                    else
                    {
                        dialogBuilder.SetMessage("No new messages");
                    }
                    //dialogBuilder.SetPositiveButton("Ok", null);
                    dialogBuilder.Show();
                    return(null);
                }
            }
            else
            {
                if (!sessionStore.ContainsSession(SelectedFriendAddress))
                {
                    // Instantiate a SessionBuilder for a remote recipientId + deviceId tuple.
                    SessionBuilder sessionBuilder = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
                                                                       identityStore, SelectedFriendAddress);
                    RetrievedPreKey preKeyPublic = RetrieveSelectedFriendPublicPreKey(SelectedFriend);
                    IdentityKey     SelectedFriendSignedPreKey = new IdentityKey(JsonConvert.DeserializeObject <byte[]>(SelectedFriend.SignedPreKey), 0);
                    PreKeyBundle    retrievedPreKey            = new PreKeyBundle(SelectedFriend.RegisterationID, 1, preKeyPublic.PrekeyID, preKeyPublic.PublicPreKey.getPublicKey()
                                                                                  , SelectedFriend.SignedPreKeyID, SelectedFriendSignedPreKey.getPublicKey(), JsonConvert.DeserializeObject <byte[]>(SelectedFriend.SignedPreKeySignature)
                                                                                  , new IdentityKey(JsonConvert.DeserializeObject <byte[]>(SelectedFriend.IdentityKey), 0));
                    // Build a session with a PreKey retrieved from the server.
                    sessionBuilder.process(retrievedPreKey);
                }
                return(null);
            }
        }
Esempio n. 6
0
        private byte[] getMac(uint messageVersion,
                        IdentityKey senderIdentityKey,
                        IdentityKey receiverIdentityKey,
                        byte[] macKey, byte[] serialized)
        {
            try
            {
                MemoryStream stream = new MemoryStream();
                if (messageVersion >= 3)
                {
                    byte[] sik = senderIdentityKey.getPublicKey().serialize();
                    stream.Write(sik, 0, sik.Length);
                    byte[] rik = receiverIdentityKey.getPublicKey().serialize();
                    stream.Write(rik, 0, rik.Length);
                }

                stream.Write(serialized, 0, serialized.Length);
                byte[] fullMac = Sign.sha256sum(macKey, stream.ToArray());
                return ByteUtil.trim(fullMac, MAC_LENGTH);
            }
            catch (/*NoSuchAlgorithmException | java.security.InvalidKey*/Exception e)
            {
                throw new Exception(e.Message);
            }
        }