public void TestDisposal() { // this test is still bad. // "default" disposal byte[] symkey = SecretBox.GenerateKey(); SymmetricEncrypter abc = new SymmetricEncrypter(symkey); abc.Dispose(); SymmetricEncrypter def; try { def = new SymmetricEncrypter("Not a valid base64 code triggering an exception!"); } catch (FormatException) { // disposal is called although constructor failed. } bool exceptionThrown = false; try { def = null; } catch (Exception) { exceptionThrown = true; } _ = new SymmetricEncrypter(symkey); Assert.IsFalse(exceptionThrown); }
public void VerifyLibhydrogenEncryptedMessageCanBeDecrypted() { var sb = new SecretBox(); // Generate a key var key = new byte[SecretBox.KeyBytes]; sb.GenerateKey(key); // Generate a message to encrypt var message = Encoding.UTF8.GetBytes("You are old Father William, the young man said"); const int messageId = 1; const string context = "test"; // Buffer to hold the ciphertext var ciphertext = new byte[sb.CalculateCiphertextLength(message.Length)]; // Encrypt using libhydrogen var result = hydro_secretbox_encrypt( ciphertext, message, message.Length, messageId, context, key); // Verify that some ciphertext was generated Assert.That(ciphertext, Is.Not.All.Zero); Assert.That(result, Is.EqualTo(0)); // Decrypt using SecretBox var decryptedMessage = new byte[message.Length]; sb.Decrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId); // Verify the decrypt was successful Assert.That(decryptedMessage, Is.EqualTo(message)); }
public void VerifyDecryptFailsWithInvalidParameters() { // Encrypt a message var sb = new SecretBox(); var key = new byte[KeyBytes]; sb.GenerateKey(key); var message = Encoding.UTF8.GetBytes("You are old Father William, the young man said"); const int messageId = 1; const string context = "test"; var ciphertext = new byte[sb.CalculateCiphertextLength(message.Length)]; sb.Encrypt(ciphertext, message, message.Length, key, context, messageId); // Buffer to hold decrypted message var decryptedMessage = new byte[message.Length]; // CiphertextLength is incorrect Assert.That( () => sb.Decrypt(decryptedMessage, ciphertext, HeaderBytes, key, context, messageId), Throws.TypeOf <CryptographicException>().With.Message.EqualTo("MAC check failed")); Assert.That( sb.TryDecrypt(decryptedMessage, ciphertext, HeaderBytes, key, context, messageId), Is.False); // MessageId is incorrect Assert.That( () => sb.Decrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, 2), Throws.TypeOf <CryptographicException>().With.Message.EqualTo("MAC check failed")); // Verify the decrypted message is not equal to the message, as a failed MAC check should not // leak the plaintext Assert.That(decryptedMessage, Is.Not.EqualTo(message)); Assert.That( sb.TryDecrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, 2), Is.False); Assert.That(decryptedMessage, Is.Not.EqualTo(message)); // Key is invalid key[0]++; Assert.That( () => sb.Decrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId), Throws.TypeOf <CryptographicException>().With.Message.EqualTo("MAC check failed")); Assert.That( sb.TryDecrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId), Is.False); key[0]--; // Ciphertext is invalid ciphertext[12]++; Assert.That( () => sb.Decrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId), Throws.TypeOf <CryptographicException>().With.Message.EqualTo("MAC check failed")); Assert.That( sb.TryDecrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId), Is.False); }
public void SecretBoxOpenWithGeneratedDataTest() { var key = SecretBox.GenerateKey(); var nonce = SecretBox.GenerateNonce(); String message = "Hello, World!"; byte[] plainText = System.Text.Encoding.UTF8.GetBytes(message); byte[] cipherText = SecretBox.Create(plainText, nonce, key); byte[] decrypted = SecretBox.Open(cipherText, nonce, key); Assert.AreEqual(plainText.ToString(), decrypted.ToString()); }
public void EncryptAndDecryptWithADTest() { String message = "Hello, World!"; byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message); byte[] ad = System.Text.Encoding.UTF8.GetBytes("Additional Data"); var key = SecretBox.GenerateKey(); var nonce = SecretAead.GenerateNonce(); var encrypted = SecretAead.Encrypt(byteMessage, nonce, key, ad); var decrypted = SecretAead.Decrypt(encrypted, nonce, key, ad); Assert.AreEqual(byteMessage.ToString(), decrypted.ToString()); encrypted = SecretAead.Encrypt(message, nonce, key, ad); decrypted = SecretAead.Decrypt(encrypted, nonce, key, ad); Assert.AreEqual(byteMessage.ToString(), decrypted.ToString()); }
private void metroButton2_Click(object sender, EventArgs e) { if (txt_name.Text == "" || txt_password.Text == "") { MessageBox.Show("Please provide Name and a password"); return; } try { //Create SqlConnection SqlConnection con = new SqlConnection(cs); SqlCommand cmd = new SqlCommand("INSERT INTO tbl_list (list_name,list_password,list_key,list_nonce) VALUES (@list_name,@list_password,@list_key,@list_nonce)", con); var list_nonce = SecretBox.GenerateNonce(); //24 byte nonce var list_key = SecretBox.GenerateKey(); //32 byte key var message = txt_password.Text; //encrypt the message var ciphertext = SecretBox.Create(message, list_nonce, list_key); cmd.Parameters.AddWithValue("@list_name", txt_name.Text); cmd.Parameters.AddWithValue("@list_password", ciphertext); cmd.Parameters.AddWithValue("@list_key", list_key); cmd.Parameters.AddWithValue("@list_nonce", list_nonce); Console.WriteLine(); Console.WriteLine("Original data: " + message); Console.WriteLine("Encrypting and writing to disk..."); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); if (i != 0) { MessageBox.Show("Password Saved"); BindGridPasswords(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void EncryptAndDecryptTest() { String message = "Hello, World!"; byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message); var key = SecretBox.GenerateKey(); var nonce = SecretAead.GenerateNonce(); var encrypted = SecretAead.Encrypt(byteMessage, nonce, key); var decrypted = SecretAead.Decrypt(encrypted, nonce, key); Assert.AreEqual(byteMessage.ToString(), decrypted.ToString()); var newEncrypted = SecretAead.Encrypt(message, nonce, key); Assert.AreEqual(Convert.ToBase64String(encrypted), Convert.ToBase64String(newEncrypted)); decrypted = SecretAead.Decrypt(newEncrypted, nonce, key); Assert.AreEqual(byteMessage.ToString(), decrypted.ToString()); }
/// <summary> /// Initialize the EncryptedFileHeader for encryption. /// </summary> /// <param name="currentVersion">The StreamCryptor version.</param> /// <param name="nonceLength">The length which nonces will be generated.</param> /// <param name="chunkBaseNonceLength">The length of the base nonce.</param> /// <param name="unencryptedFileLength">The length of unencrypted file.</param> /// <param name="senderPrivateKey">The senders private key.</param> /// <param name="senderPublicKey">The senders public key.</param> /// <param name="recipientPublicKey">The recipient public key.</param> public EncryptedFileHeader(int currentVersion, int nonceLength, int chunkBaseNonceLength, long unencryptedFileLength, byte[] senderPrivateKey, byte[] senderPublicKey, byte[] recipientPublicKey) { //set the version this.Version = currentVersion; //get some ephemeral key fot this file this.UnencryptedEphemeralKey = SecretBox.GenerateKey(); //generate a nonce for the encrypted ephemeral key this.EphemeralNonce = Sodium.SodiumCore.GetRandomBytes(nonceLength); //generate a nonce for encypting the file name this.FilenameNonce = Sodium.SodiumCore.GetRandomBytes(nonceLength); //encrypt the ephemeral key with our public box this.Key = Sodium.PublicKeyBox.Create(this.UnencryptedEphemeralKey, this.EphemeralNonce, senderPrivateKey, recipientPublicKey); //set the senders public key to the header, to guarantee the recipient can decrypt it this.SenderPublicKey = senderPublicKey; //a random base nonce (16 byte), which will be filled up to 24 byte in every chunk this.BaseNonce = SodiumCore.GetRandomBytes(chunkBaseNonceLength); //set unencrypted file length to the file header this.UnencryptedFileLength = unencryptedFileLength; }
public void VerifyMessageCanBeEncryptedAndDecrypted() { var sb = new SecretBox(); // Generate a key var key = new byte[KeyBytes]; sb.GenerateKey(key); // Generate a message to encrypt var message = Encoding.UTF8.GetBytes("You are old Father William, the young man said"); const int messageId = 1; const string context = "test"; // Buffer to hold the ciphertext var ciphertext = new byte[sb.CalculateCiphertextLength(message.Length)]; // Encrypt sb.Encrypt(ciphertext, message, message.Length, key, context, messageId); // Buffer to hold decrypted message var decryptedMessage = new byte[message.Length]; // Decrypt sb.Decrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId); // Verify the decrypted message Assert.That(decryptedMessage, Is.EqualTo(message)); // Decrypt using TryDecrypt Array.Clear(decryptedMessage, 0, decryptedMessage.Length); var result = sb.TryDecrypt(decryptedMessage, ciphertext, ciphertext.Length, key, context, messageId); // Verify the decrypted message Assert.That(decryptedMessage, Is.EqualTo(message)); Assert.That(result, Is.True); }
public void SecretBoxGenerateKeyTest() { Assert.AreEqual(32, SecretBox.GenerateKey().Length); }
public static string GenerateKey() { var key = SecretBox.GenerateKey(); return(Convert.ToBase64String(key)); }
public void TestBOEncryption() { //hubnet.StaticLogger.Logger = new Microsoft.Extensions.Logging.Debug.DebugLogger("Testlogger", (log, level) => { return true; }); string[] files = Directory.GetFiles($"encrypterTests/bo/", "*.json"); // foreach (string testFile in files) { JObject json; using (StreamReader r = new StreamReader(testFile)) { string jsonString = r.ReadToEnd(); json = JsonConvert.DeserializeObject <JObject>(jsonString); } Assert.IsNotNull(json, $"The content of file {testFile} seems to be no valid JSON."); string boType = (string)json["boTyp"]; Assert.IsNotNull(boType, $"The JSON content of file {testFile} is missing the obligatory 'boTyp' attribute."); BusinessObject bo = BO4E.BoMapper.MapObject(boType, json); Assert.IsNotNull(bo, $"The business object in file {testFile} is not a valid BO4E."); /******* symmetric test ******/ byte[] symkey = SecretBox.GenerateKey(); string symkeyString = Convert.ToBase64String(symkey); EncryptedObject eo; using (SymmetricEncrypter se0 = new SymmetricEncrypter(symkey)) { eo = se0.Encrypt(bo, "Associated"); } BusinessObject boDecrypted; using (SymmetricEncrypter se1 = new SymmetricEncrypter(symkeyString)) { boDecrypted = se1.Decrypt(eo); } string expectedString = JsonConvert.SerializeObject(bo); string actualString = JsonConvert.SerializeObject(boDecrypted); Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!"); /******* asymmetric test ******/ var asykeyPairSender = PublicKeyBox.GenerateKeyPair(); var asykeyPairRecipient = PublicKeyBox.GenerateKeyPair(); using (AsymmetricEncrypter asyenc = new AsymmetricEncrypter(asykeyPairSender)) { eo = asyenc.Encrypt(bo, Convert.ToBase64String(asykeyPairRecipient.PublicKey)); } using (AsymmetricEncrypter asydec = new AsymmetricEncrypter(asykeyPairRecipient.PrivateKey)) { boDecrypted = asydec.Decrypt(eo); } expectedString = JsonConvert.SerializeObject(bo); actualString = JsonConvert.SerializeObject(boDecrypted); Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!"); /******* X509 + RSA test ******/ // encrypt (without needing a private key) X509Certificate2 x509certPubl = new X509Certificate2(X509Certificate2.CreateFromCertFile("encrypterTests/publickey.cer")); using (X509AsymmetricEncrypter xasyEnc = new X509AsymmetricEncrypter(x509certPubl))// encrypter needs no private key! { eo = xasyEnc.Encrypt(bo); } // decrypt (using a private key) AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(@"encrypterTests/privatekey.pem")) // file containing RSA PKCS1 private key { keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); } // openssl genrsa -out privatekey.pem 2048 // openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 3650 using (X509AsymmetricEncrypter xasydec = new X509AsymmetricEncrypter(keyPair.Private)) { boDecrypted = xasydec.Decrypt(eo); } expectedString = JsonConvert.SerializeObject(bo); actualString = JsonConvert.SerializeObject(boDecrypted); Assert.IsTrue(expectedString == actualString, "Original and encrypted->decrypted object do not match!"); /********** X509 + RSA multiple recipients *******/ X509Certificate2 x509certPubl2 = new X509Certificate2(X509Certificate2.CreateFromCertFile("encrypterTests/publickey2.cer")); EncryptedObject eoMultiple; using (X509AsymmetricEncrypter xasyEncMultiple = new X509AsymmetricEncrypter(new HashSet <X509Certificate2> { x509certPubl, x509certPubl2 })) // encrypter needs not private key! { eoMultiple = xasyEncMultiple.Encrypt(bo); } // decrypt (using both private keys) AsymmetricCipherKeyPair keyPair2; using (var reader = File.OpenText(@"encrypterTests/privatekey2.pem")) // file containing RSA PKCS1 private key { keyPair2 = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); } using (X509AsymmetricEncrypter xasydecMultiple = new X509AsymmetricEncrypter(keyPair.Private)) { using X509AsymmetricEncrypter xasydecMultiple2 = new X509AsymmetricEncrypter(keyPair2.Private); boDecrypted = xasydecMultiple.Decrypt(eoMultiple); BusinessObject boDecrypted2 = xasydecMultiple2.Decrypt(eoMultiple); string actualString2 = JsonConvert.SerializeObject(boDecrypted2); Assert.AreEqual(expectedString, actualString2, "Original and encrypted->decrypted object do not match!"); } expectedString = JsonConvert.SerializeObject(bo); actualString = JsonConvert.SerializeObject(boDecrypted); Assert.AreEqual(expectedString, actualString, "Original and encrypted->decrypted object do not match!"); } }
/// <summary> /// Generate a 32 byte key to use for encryption /// </summary> public static Maybe <byte[]> GenerateKey() => F.Some( () => SecretBox.GenerateKey(), e => new M.GeneratingKeyExceptionMsg(e) );