-
-
Save pomarc/1ee00ddecd36e51fac07 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 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