-
-
Save pomarc/5a53022075442cafded9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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