Exemplo n.º 1
0
 public static byte[] Encrypt(byte[] bytes, string publicKey)
 {
     using (var rsa = new RSACryptoServiceProvider())
     {
         rsa.FromXmlString(publicKey);
         var retBytes = rsa.EncryptValue(bytes);
         return(retBytes);
     }
 }
        /// <summary>
        /// Encrypts the input.
        /// </summary>
        /// <param name="input">the bytes to encrypt.</param>
        /// <returns>encrypted bytes.</returns>
        /// <exception cref="ArgumentNullException">if <paramref name="input"/> is null or Length == 0.</exception>
        public override byte[] EncryptValue(byte[] input)
        {
            if (input == null || input.Length == 0)
            {
                throw LogHelper.LogArgumentNullException(nameof(input));
            }

            return(_rsa.EncryptValue(input));
        }
Exemplo n.º 3
0
    public static String encrypt(String encryptThis)
    {
        string b64EncryptThis = Utilities.Base64Encode(encryptThis);

        //Encrypt the symmetric key and IV.
        byte[] encryptedString = encrypter.EncryptValue(Convert.FromBase64String(b64EncryptThis));

        //Add the encrypted test string to the form
        return(Convert.ToBase64String(encryptedString));
    }
Exemplo n.º 4
0
        /// <summary>
        /// RSA private key encryption
        /// </summary>
        /// <param name="dataBytes">Need to encrypt data</param>
        /// <returns></returns>
        public string EncryptByPrivateKey(byte[] dataBytes)
        {
            if (PrivateRsa is null)
            {
                throw new ArgumentException("private key can not null");
            }

            var resBytes = PrivateRsa.EncryptValue(dataBytes);

            return(Convert.ToBase64String(resBytes));
        }
Exemplo n.º 5
0
        public async Task <HttpStatusCode> sendMessage(string recipient, string message)
        {
            string currentPub = await getPublicKey(recipient);

            if (currentPub != string.Empty)
            {
                TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
                provider.KeySize = 128;
                provider.GenerateIV();
                var iv = provider.IV;
                provider.GenerateKey();
                var key = provider.Key;
                var aes = AesManaged.Create();
                aes.BlockSize = 128;
                aes.Mode      = CipherMode.CBC;
                var encryptor = aes.CreateEncryptor();
                var cipher    = encryptor.TransformFinalBlock(Encoding.Default.GetBytes(message), 0, Encoding.Default.GetBytes(message).Length);

                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    var           pubkey     = getKeyFromString(currentPub);
                    RSAParameters parameters = new RSAParameters();
                    parameters.Exponent = pubkey.Exponent.ToByteArrayUnsigned();
                    parameters.Modulus  = pubkey.Modulus.ToByteArrayUnsigned();
                    RSA.ImportParameters(parameters);
                    var           key_recipient_enc = RSA.EncryptValue(key);
                    SHA256Managed hasher            = new SHA256Managed();
                    hasher.ComputeHash(Encoding.Default.GetBytes(private_key));
                    hasher.ComputeHash(Encoding.Unicode.GetBytes(login));
                    hasher.ComputeHash(cipher);
                    hasher.ComputeHash(iv);
                    hasher.ComputeHash(key_recipient_enc);
                    var           sig_recipient = hasher.Hash;
                    SHA256Managed hasher2       = new SHA256Managed();
                    hasher2.ComputeHash(Encoding.Unicode.GetBytes(login));
                    hasher2.ComputeHash(cipher);
                    hasher2.ComputeHash(iv);
                    hasher2.ComputeHash(key_recipient_enc);
                    hasher2.ComputeHash(sig_recipient);
                    var timestamp      = getUnixTimestamp();
                    var timestampBytes = Encoding.Default.GetBytes(timestamp.ToString());
                    hasher2.ComputeHash(timestampBytes);
                    hasher2.ComputeHash(Encoding.Unicode.GetBytes(recipient));
                    var     sig_service = hasher2.Hash;
                    dynamic envelope    = new ExpandoObject();
                    envelope.sender            = login;
                    envelope.content_enc       = Base64Encode(message);
                    envelope.key_recipient_enc = Encoding.UTF8.GetString(key_recipient_enc);
                    envelope.sig_recipient     = Encoding.UTF8.GetString(sig_recipient);
                    envelope.timestamp         = timestamp;
                    envelope.sig_service       = Encoding.UTF8.GetString(sig_service);
                    envelope.recipient         = recipient;
                    string json = JsonConvert.SerializeObject(envelope);
                    using (var client = new HttpClient())
                    {
                        var result = await client.PostAsync("https://webengserver.herokuapp.com/" + recipient + "/message", json);

                        return(result.StatusCode);
                    }
                }
            }
            return(HttpStatusCode.BadRequest);
        }
Exemplo n.º 6
0
 public byte[] DecryptToBytes(byte[] message)
 {
     return(_rsa.EncryptValue(message));
 }
Exemplo n.º 7
0
    private void attemptExitFromLevel()
    {
        GameObject exitSign     = GameObject.FindGameObjectWithTag("Exit");
        Vector2    distFromExit = transform.position - exitSign.transform.position;

        if (Vector2.SqrMagnitude(distFromExit) < 0.25)
        {
            //Calculate time elapsed during the game level
            stopWatch.Stop();
            int timeElapsed = unchecked ((int)(stopWatch.ElapsedMilliseconds / 1000));

            //Calculate the points for the game level
            //Score based on: time taken, num crashes, steps taken, trying(num echoes played on same spot)
            //Finish in less than 15 seconds => full score
            //For every 10 seconds after 15 seconds, lose 100 points
            //For every crash, lose 150 points
            //For every step taken over the optimal steps, lose 50 points
            //Max score currently is 1500 points
            int score = 1500;
            if (timeElapsed > 15)
            {
                score = score - (((timeElapsed - 16) / 10) + 1) * 100;
            }
            if (numCrashes > 0)
            {
                score = score - numCrashes * 150;
            }
            //Check if the score went below 0
            if (score < 0)
            {
                score = 0;
            }
            //TODO
            //if numSteps > numOptimalSteps, then adjust score
            //Calculate optimal steps by getting start position and end position
            //and calculate the number of steps



            //Send the crash count data and level information to server
            //string dataEndpoint = "http://cmuecholocation.herokuapp.com/storeGameLevelData";
            string dataEndpoint = "http://128.237.139.120:8000/storeGameLevelData";

            WWWForm form = new WWWForm();
            form.AddField("userName", SystemInfo.deviceUniqueIdentifier);
            form.AddField("crashCount", numCrashes);
            form.AddField("stepCount", numSteps);
            form.AddField("currentLevel", curLevel);
            //Send the name of the echo files used in this level and the counts
            form.AddField("echoFileNames", getEchoNames());

            //Send the details of the crash locations
            form.AddField("crashLocations", crashLocs);
            form.AddField("timeElapsed", timeElapsed);

            form.AddField("score", score);

            //Start of the encryption data
            try {
                string testToEncrypt = Base64Encode("This is a test string");
                //initialze the byte arrays to the public key information.
                string publicKeyString = "iqKXThQvzLKgG0FQXuznGk4nEyFlE9VGmFIzkQyX9n3giHXJoqln4pZASPH3XnJX7ZOxmXXGskjrAYXLD2BZ8eZFkEmNj0GTC9kbDZzcjd+3Lc6P32J7MjfD7dIyPH8IUB9ELtL2MZ36kZrLrf3c2q2pQIl4s5k0Ro2F2aXWB+s=";
                byte[] publicKeyBytes  = Convert.FromBase64String(publicKeyString);

                byte[] Exponent = { 17 };

                //Create a new instance of RSACryptoServiceProvider.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Create a new instance of RSAParameters.
                RSAParameters RSAKeyInfo = new RSAParameters();

                //Set RSAKeyInfo to the public key values.
                RSAKeyInfo.Modulus  = publicKeyBytes;
                RSAKeyInfo.Exponent = Exponent;

                //Import key parameters into RSA.
                RSA.ImportParameters(RSAKeyInfo);

                //Create a new instance of the RijndaelManaged class.
                RijndaelManaged RM = new RijndaelManaged();

                //Encrypt the symmetric key and IV.
                byte[] encryptedTestString = RSA.EncryptValue(Convert.FromBase64String(testToEncrypt));

                //Add the encrypted test string to the form
                form.AddField("testEncrypt", Convert.ToBase64String(encryptedTestString));
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                form.AddField("testEncrypt", e.Message);
            }

            WWW www = new WWW(dataEndpoint, form);
            StartCoroutine(WaitForRequest(www));

            //Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
            restarted = true;
            Invoke("Restart", restartLevelDelay);
            //Disable the player object since level is over.
            enabled = false;
            AudioSource.PlayClipAtPoint(winSound, transform.localPosition, 0.3f);

            //Reset the crash count
            numCrashes = 0;
        }
    }