Skip to content

Instantly share code, notes, and snippets.

@pomarc
Created July 31, 2014 07:11
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/1ee00ddecd36e51fac07 to your computer and use it in GitHub Desktop.
Save pomarc/1ee00ddecd36e51fac07 to your computer and use it in GitHub Desktop.
static byte[] EncryptAsymmetric(string message, byte[] publicKey, byte[] secretKey, byte[] nonce)
{
// First convert the string to a byte array:
byte[] messageBuffer = UTF8Encoding.UTF8.GetBytes(message);
// Preallocate array and accomodate space for zero padding.
var unencryptedData = new byte[CryptoBox.ZeroBytes + messageBuffer.Length];
Array.Copy(messageBuffer, 0, unencryptedData, CryptoBox.ZeroBytes, messageBuffer.Length);
// Preallocate output buffer
var encryptedData = new byte[unencryptedData.Length];
CryptoBox.Box(encryptedData, 0, unencryptedData, 0, unencryptedData.Length, nonce, publicKey, secretKey);
return encryptedData;
}
static string DecryptAsymmetric(byte[] encryptedData, byte[] publicKey, byte[] secretKey, byte[] nonce)
{
// First preallocate the data array
var decryptedData = new byte[encryptedData.Length];
if (CryptoBox.Open(decryptedData, 0, encryptedData, 0, encryptedData.Length, nonce, publicKey, secretKey)
!= 0)
{
throw new ArgumentException("Could not decrypt data");
}
// Message could be decrypted, convert byte array to string
int dataLength = (decryptedData.Length - CryptoBox.ZeroBytes);
char[] buffer = UTF8Encoding.UTF8.GetChars(decryptedData, CryptoBox.ZeroBytes, dataLength);
return new string(buffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment