Skip to content

Instantly share code, notes, and snippets.

@pomarc
Created July 31, 2014 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pomarc/5a53022075442cafded9 to your computer and use it in GitHub Desktop.
Save pomarc/5a53022075442cafded9 to your computer and use it in GitHub Desktop.
static void TestSymmetric()
{
// First we create a nonce specify the nonce and fill it with random values
var nonce = new byte[CryptoSecretBox.NonceBytes];
RandomNumberGenerator rng = RandomNumberGenerator.Create();
rng.GetBytes(nonce);
// Then we create a secret key
var key = new byte[CryptoSecretBox.KeyBytes];
rng.GetBytes(key);
//the secret message!!!
var message = "winter is coming";
//normal operations:
try
{
//encrypt
byte[] cypertext = EncryptSecretKey(message, key, nonce);
//decrypt
string decrypted = DecryptSecretKey(cypertext, key, nonce);
//test
if (decrypted == message)
{
Debug.Print("OK! the text matches");
}
else
{
Debug.Print("ERROR: this should NOT happen, ouch, the decyphered text is wrong!");
}
}
catch (Exception ex)
{
Debug.Print("ERROR: this should NOT happen!");
}
try
{
byte[] cypertext = EncryptSecretKey(message, key, nonce);
//just changes a byte in the cyphertext:
cypertext[4] =1;
string decrypted = DecryptSecretKey(cypertext, key, nonce);
Debug.Print("this should never be executed!");
}
catch (Exception ex)
{
Debug.Print(" this error SHOULD happen, the cyphertext has been tampered with, yay!");
}
try
{
byte[] cypertext = EncryptSecretKey(message, key, nonce);
//wrong key:
key[4] = 0;
string decrypted = DecryptSecretKey(cypertext, key, nonce);
Debug.Print("this should never be executed!");
}
catch (Exception ex)
{
Debug.Print("this error SHOULD happen, the key has been changed, yay!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment