public static byte[] EncryptWithChecksum(PrivateKey privateKey, PublicKey publicKey, UInt64 nonce, string message) { byte[] shareSecret = privateKey.SharedSecret(publicKey); byte[] sharedSecretUTF8Bytes = Encoding.UTF8.GetBytes(Hex.BytesToHex(shareSecret)); byte[] nonceBytes = Encoding.UTF8.GetBytes("" + nonce); byte[] seed = nonceBytes.Concat(sharedSecretUTF8Bytes).ToArray(); string hash = Hex.BytesToHex(Hash.SHA512(seed)); byte[] key = Hex.HexToBytes(hash.Substring(0, 64)); byte[] iv = Hex.HexToBytes(hash.Substring(64, 32)); byte[] encodedMsg = Encoding.UTF8.GetBytes(message); byte[] checksum = Hash.SHA256(encodedMsg).Take(4).ToArray(); return(EncryptStringToBytes(checksum.Concat(encodedMsg).ToArray(), key, iv)); }
public static string DecryptWithChecksum(PrivateKey privateKey, PublicKey publicKey, UInt64 nonce, byte[] payload) { byte[] shareSecret = privateKey.SharedSecret(publicKey); byte[] sharedSecretUTF8Bytes = Encoding.UTF8.GetBytes(Hex.BytesToHex(shareSecret)); byte[] nonceBytes = Encoding.UTF8.GetBytes("" + nonce); byte[] seed = nonceBytes.Concat(sharedSecretUTF8Bytes).ToArray(); string hash = Hex.BytesToHex(Hash.SHA512(seed)); byte[] key = Hex.HexToBytes(hash.Substring(0, 64)); byte[] iv = Hex.HexToBytes(hash.Substring(64, 32)); byte[] decryptedMsg = DecryptStringFromBytes(payload, key, iv); byte[] checksum = decryptedMsg.Take(4).ToArray(); byte[] message = decryptedMsg.Skip(4).ToArray(); byte[] newChecksum = Hash.SHA256(message).Take(4).ToArray(); if (!checksum.SequenceEqual(newChecksum)) { throw new Exception($"Invalid checksum, expected {Hex.BytesToHex(newChecksum)}, got {Hex.BytesToHex(checksum)}"); } return(Encoding.UTF8.GetString(message)); }