public byte[] Decrypt(byte[] encrypted) { if (encrypted is null) { throw new ArgumentNullException(nameof(encrypted)); } if (encrypted.Length < 85) { throw new ArgumentException("Encrypted text is invalid, it should be length >= 85."); } var magic = encrypted.SafeSubarray(0, 4); var ephemeralPubkeyBytes = encrypted.SafeSubarray(4, 33); var cipherText = encrypted.SafeSubarray(37, encrypted.Length - 32 - 37); var mac = encrypted.SafeSubarray(encrypted.Length - 32); if (!Utils.ArrayEqual(magic, Encoders.ASCII.DecodeData("BIE1"))) { throw new ArgumentException("Encrypted text is invalid, Invalid magic number."); } var ephemeralPubkey = new PubKey(ephemeralPubkeyBytes); var ecpoint = ephemeralPubkey.ECKey.GetPublicKeyParameters().Q; if (ecpoint.IsInfinity || !ecpoint.IsValid()) { throw new ArgumentException("Encrypted text is invalid, Invalid ephemeral public key."); } var sharedKey = Hashes.SHA512(ephemeralPubkey.GetSharedPubkey(this).ToBytes()); var iv = sharedKey.SafeSubarray(0, 16); var encryptionKey = sharedKey.SafeSubarray(16, 16); var hashingKey = sharedKey.SafeSubarray(32); var hashMAC = Hashes.HMACSHA256(hashingKey, encrypted.SafeSubarray(0, encrypted.Length - 32)); if (!Utils.ArrayEqual(mac, hashMAC)) { throw new ArgumentException("Encrypted text is invalid, Invalid mac."); } var aes = new AesBuilder().SetKey(encryptionKey).SetIv(iv).IsUsedForEncryption(false).Build(); var message = aes.Process(cipherText, 0, cipherText.Length); return(message); }
public byte[] Encrypt(byte[] message) { if (message is null) { throw new ArgumentNullException(nameof(message)); } var ephemeral = new Key(); var sharedKey = Hashes.SHA512(GetSharedPubkey(ephemeral).ToBytes()); var iv = sharedKey.SafeSubarray(0, 16); var encryptionKey = sharedKey.SafeSubarray(16, 16); var hashingKey = sharedKey.SafeSubarray(32); var aes = new AesBuilder().SetKey(encryptionKey).SetIv(iv).IsUsedForEncryption(true).Build(); var cipherText = aes.Process(message, 0, message.Length); var ephemeralPubkeyBytes = ephemeral.PubKey.ToBytes(); var encrypted = Encoders.ASCII.DecodeData("BIE1").Concat(ephemeralPubkeyBytes, cipherText); var hashMAC = Hashes.HMACSHA256(hashingKey, encrypted); return(encrypted.Concat(hashMAC)); }