public void Wipe() { var bytes = (byte[])_bytes.Clone(); CryptoBytes.Wipe(bytes); bytes.All(b => b == 0).Should().BeTrue(); }
public void RandomNonceTest() { var rnd = new Random(); var key = new byte[Snuffle.KEY_SIZE_IN_BYTES]; rnd.NextBytes(key); var aead = new XChaCha20Poly1305(key); var message = new byte[0]; var aad = new byte[0]; var ciphertexts = new HashSet <string>(); var samples = 1 << 17; for (var i = 0; i < samples; i++) { var ct = aead.Encrypt(message, aad); var ctHex = CryptoBytes.ToHexStringLower(ct); Assert.IsFalse(ciphertexts.Contains(ctHex)); ciphertexts.Add(ctHex); } Assert.AreEqual(samples, ciphertexts.Count); }
public void EncryptDecryptLongMessagesWithNonceTest() { var rnd = new Random(); var dataSize = 16; while (dataSize <= (1 << 24)) { var plaintext = new byte[dataSize]; rnd.NextBytes(plaintext); var aad = new byte[dataSize / 3]; rnd.NextBytes(aad); var nonce = new byte[24]; rnd.NextBytes(nonce); var key = new byte[Snuffle.KEY_SIZE_IN_BYTES]; rnd.NextBytes(key); var aead = new XChaCha20Poly1305(key); var ciphertext = aead.Encrypt(plaintext, aad, nonce); var decrypted = aead.Decrypt(ciphertext, aad, nonce); //Assert.AreEqual(plaintext, decrypted); Assert.IsTrue(CryptoBytes.ConstantTimeEquals(plaintext, decrypted)); dataSize += 5 * dataSize / 11; } }
public void EncryptDecryptWithNonceTest() { var rnd = new Random(); var key = new byte[Snuffle.KEY_SIZE_IN_BYTES]; rnd.NextBytes(key); var aead = new XChaCha20Poly1305(key); for (var i = 0; i < 100; i++) { var message = new byte[100]; rnd.NextBytes(message); var aad = new byte[16]; rnd.NextBytes(aad); var nonce = new byte[24]; rnd.NextBytes(nonce); var ciphertext = aead.Encrypt(message, aad, nonce); var decrypted = aead.Decrypt(ciphertext, aad, nonce); //Assert.AreEqual(message, decrypted); Assert.IsTrue(CryptoBytes.ConstantTimeEquals(message, decrypted)); } }
public void ConstantTimeEqualsSegmentsSuccess() { var x = new byte[] { 1, 2, 3 }; var y = new byte[] { 1, 2, 3 }; CryptoBytes.ConstantTimeEquals(x.Pad(), y.Pad()).Should().BeTrue(); }
private void Serialize() { // transaction type. Set as null/empty bytes as it will be // updated when serializing the different transaction types. Serializer.WriteInt(TransactionType.MultisigTransaction); // version Serializer.WriteInt(TransactionVersion.VersionOne); // timestamp Serializer.WriteInt(TimeStamp); //pubKey len Serializer.WriteInt(ByteLength.PublicKeyLength); // pub key Serializer.WriteBytes(CryptoBytes.FromHexString(PublicKey.Raw)); // fee Serializer.WriteLong(Fee); // deadline Serializer.WriteInt(Deadline); Serializer.WriteInt(InnerLength); }
public static string Decode(string text, PrivateKey sk, string pk) { return(_Decode( CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(sk.Raw)), CryptoBytes.FromHexString(pk), CryptoBytes.FromHexString(text))); }
public static bool crypto_sign_verify(ReadOnlySpan <byte> sig, ReadOnlySpan <byte> m, ReadOnlySpan <byte> pk) { if ((sig[63] & 224) != 0) { return(false); } if (GroupOperations.ge_frombytes_negate_vartime(out var A, pk) != 0) { return(false); } var hasher = new Sha512(); hasher.Update(sig.Slice(0, 32)); hasher.Update(pk.Slice(0, 32)); hasher.Update(m); Span <byte> h = stackalloc byte[64]; hasher.Finish(h); ScalarOperations.sc_reduce(h); GroupOperations.ge_double_scalarmult_vartime(out var R, h, in A, sig.Slice(32, 32)); Span <byte> checkr = stackalloc byte[32]; GroupOperations.ge_tobytes(checkr, in R); var result = CryptoBytes.ConstantTimeEquals(checkr, sig, 32); CryptoBytes.Wipe(h); CryptoBytes.Wipe(checkr); return(result); }
public void EncryptDecryptNBlocksTest() { // Arrange var rnd = new Random(); var key = new byte[Snuffle.KEY_SIZE_IN_BYTES]; for (var i = 0; i < 64; i++) { rnd.NextBytes(key); var cipher = new ChaCha20(key, 0); for (var j = 0; j < 64; j++) { var expectedInput = new byte[rnd.Next(300)]; rnd.NextBytes(expectedInput); // Act var output = cipher.Encrypt(expectedInput); var actualInput = cipher.Decrypt(output); // Assert //Assert.AreEqual(expectedInput, actualInput); Assert.IsTrue(CryptoBytes.ConstantTimeEquals(expectedInput, actualInput)); } } }
public static string PublicKeyToAddress(byte[] publicKey, int networkPrefix) { KeccakDigest shaDigest = new KeccakDigest(256); byte[] bytesFirst = new byte[32]; shaDigest.BlockUpdate(publicKey, 0, 32); shaDigest.DoFinal(bytesFirst, 0); RipeMD160Digest digestRipeMd160 = new RipeMD160Digest(); byte[] bytesSecond = new byte[20]; digestRipeMd160.BlockUpdate(bytesFirst, 0, 32); digestRipeMd160.DoFinal(bytesSecond, 0); byte[] bytesThird = CryptoBytes.FromHexString( string.Concat(networkPrefix, CryptoBytes.ToHexStringLower(bytesSecond)) ); byte[] bytesFourth = new byte[32]; shaDigest.BlockUpdate(bytesThird, 0, 21); shaDigest.DoFinal(bytesFourth, 0); byte[] bytesFifth = new byte[4]; Array.Copy(bytesFourth, 0, bytesFifth, 0, 4); byte[] bytesSixth = new byte[25]; Array.Copy(bytesThird, 0, bytesSixth, 0, 21); Array.Copy(bytesFifth, 0, bytesSixth, 21, 4); return(Base32.Encode(bytesSixth).ToUpper()); }
public static void crypto_sign_prehashed( byte[] sig, byte[] m, int mlen, byte[] sk, byte[] pk ) { byte[] r, hram; GroupElementP3 R; var hasher = new Sha512(); { hasher.Init(); hasher.Update(sk, 32, 32); hasher.Update(m, 0, mlen); r = hasher.Finalize(); ScalarOperations.sc_reduce(r); GroupOperations.ge_scalarmult_base(out R, r, 0); GroupOperations.ge_p3_tobytes(sig, 0, ref R); hasher.Init(); hasher.Update(sig, 0, 32); hasher.Update(pk, 0, 32); hasher.Update(m, 0, mlen); hram = hasher.Finalize(); ScalarOperations.sc_reduce(hram); var s = new byte[32]; //todo: remove allocation Array.Copy(sig, 32, s, 0, 32); ScalarOperations.sc_muladd(s, hram, sk, r); Array.Copy(s, 0, sig, 32, 32); CryptoBytes.Wipe(s); } }
public void ConstantTimeEqualsSegmentsSuccess() { var x = new byte[] { 1, 2, 3 }; var y = new byte[] { 1, 2, 3 }; Assert.IsTrue(CryptoBytes.ConstantTimeEquals(x.Pad(), y.Pad())); }
/// <summary> /// Tries to commit a transaction to the DAppChain. /// </summary> /// <param name="tx">Transaction to commit.</param> /// <returns>Commit metadata.</returns> /// <exception cref="InvalidTxNonceException">Thrown when transaction is rejected by the DAppChain due to a bad nonce.</exception> private async Task <BroadcastTxResult> TryCommitTxAsync(IMessage tx) { byte[] txBytes = tx.ToByteArray(); if (this.TxMiddleware != null) { txBytes = await this.TxMiddleware.Handle(txBytes); } string payload = CryptoBytes.ToBase64String(txBytes); var result = await this.writeClient.SendAsync <BroadcastTxResult, string[]>("broadcast_tx_commit", new string[] { payload }); if (result != null) { if (result.CheckTx.Code != 0) { if ((result.CheckTx.Code == 1) && (result.CheckTx.Error == "sequence number does not match")) { throw new InvalidTxNonceException(result.CheckTx.Code, result.CheckTx.Error); } throw new TxCommitException(result.CheckTx.Code, result.CheckTx.Error); } if (result.DeliverTx.Code != 0) { throw new TxCommitException(result.DeliverTx.Code, result.DeliverTx.Error); } } return(result); }
/// <summary> /// Queries the current state of a contract. /// </summary> /// <typeparam name="T">The expected response type, must be deserializable with Newtonsoft.Json.</typeparam> /// <param name="contract">Address of the contract to query.</param> /// <param name="queryParams">Query parameters object.</param> /// <returns>Deserialized response.</returns> public async Task <T> QueryAsync <T>(Address contract, IMessage query = null) { var contractAddr = "0x" + CryptoUtils.BytesToHexString(contract.Local.ToByteArray()); var queryBytes = CryptoBytes.ToBase64String(query.ToByteArray()); var req = new QueryJsonRpcRequest("query", contractAddr, queryBytes, Guid.NewGuid().ToString()); string body = JsonConvert.SerializeObject(req); Logger.Log(LogTag, "Query body: " + body); byte[] bodyRaw = new UTF8Encoding().GetBytes(body); using (var r = new UnityWebRequest(this.readUrl, "POST")) { r.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); r.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); r.SetRequestHeader("Content-Type", "application/json"); await r.SendWebRequest(); this.HandleError(r); if (r.downloadHandler != null && !String.IsNullOrEmpty(r.downloadHandler.text)) { Logger.Log(LogTag, "Response: " + r.downloadHandler.text); var resp = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(r.downloadHandler.text); return(resp.Result); } } return(default(T)); }
public void Wipe() { var bytes = (byte[])_bytes.Clone(); CryptoBytes.Wipe(bytes); Assert.IsTrue(bytes.All(b => b == 0)); }
public void HChaCha20BlockTestVector() { // https://tools.ietf.org/html/draft-irtf-cfrg-xchacha-03#section-2.2.1 // Arrange var key = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty)); var nonce = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27".Replace(":", string.Empty)); var cipher = new XChaCha20(key, 0); // Act var subKey = new byte[32]; cipher.HChaCha20(subKey, nonce); var state = subKey.ToUInt16Array(); //var stateHex = CryptoBytes.ToHexStringLower(subKey.ToArray()); // Assert // HChaCha20 returns only the first and last rows var expectedState = new uint[] { 0x423b4182, 0xfe7bb227, 0x50420ed3, 0x737d878a, //0x0aa76448, 0x7954cdf3, 0x846acd37, 0x7b3c58ad, //0x77e35583, 0x83e77c12, 0xe0076a2d, 0xbc6cd0e5, 0xd5e4f9a0, 0x53a8748a, 0x13c42ec1, 0xdcecd326 }; // Same as above but in HEX //var expectedStateHex = "82413b4" + "227b27bfe" + "d30e4250" + "8a877d73" // + "a0f9e4d" + "58a74a853" + "c12ec413" + "26d3ecdc"; state.Should().BeEquivalentTo(expectedState); //stateHex.Should().Be(expectedStateHex); }
public static void crypto_sign_keypair(byte[] pk, int pkoffset, byte[] sk, int skoffset, byte[] seed, int seedoffset) { GroupElementP3 A; int i; Array.Copy(seed, seedoffset, sk, skoffset, 32); var blake2bConfig = new Blake2BConfig { OutputSizeInBytes = 64 }; var hasher = Blake2B.Create(blake2bConfig); hasher.Update(sk, skoffset, 32); byte[] h = hasher.Finish(); //byte[] h = Sha512.Hash(sk, skoffset, 32);//ToDo: Remove alloc ScalarOperations.sc_clamp(h, 0); GroupOperations.ge_scalarmult_base(out A, h, 0); GroupOperations.ge_p3_tobytes(pk, pkoffset, ref A); for (i = 0; i < 32; ++i) { sk[skoffset + 32 + i] = pk[pkoffset + i]; } CryptoBytes.Wipe(h); }
public void HChaCha20StateTestVector() { // https://tools.ietf.org/html/draft-irtf-cfrg-xchacha-03#section-2.2.1 // Arrange var key = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty)); var nonce = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27".Replace(":", string.Empty)); var cipher = new XChaCha20(key, 0); // Act var initialState = new uint[16]; cipher.HChaCha20InitialState(initialState, nonce); // Assert var expectedInitialState = new uint[] { 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574, 0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c, 0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c, 0x09000000, 0x4a000000, 0x00000000, 0x27594131 }; initialState.Should().BeEquivalentTo(expectedInitialState); }
private void Serialize() { TotalBytesLength += 4; Serializer.WriteInt(Data.Modifications.Count); foreach (var mod in Data.Modifications) { TotalBytesLength += StructureLength.AggregateModification + ByteLength.FourBytes; Serializer.WriteInt(StructureLength.AggregateModification); Serializer.WriteInt(mod.ModificationType); Serializer.WriteInt(ByteLength.PublicKeyLength); Serializer.WriteBytes(CryptoBytes.FromHexString(mod.PublicKey.Raw)); } if (Data.RelativeChange != 0) { TotalBytesLength += StructureLength.RelativeChange + ByteLength.FourBytes; Serializer.WriteInt(StructureLength.RelativeChange); Serializer.WriteInt(Data.RelativeChange); } else { TotalBytesLength += ByteLength.FourBytes; Serializer.WriteInt(ByteLength.Zero); } }
public void Poly1305TestVector4() { // Tests against the test vector 4 in Appendix A.3 of RFC 7539. // https://tools.ietf.org/html/rfc7539#appendix-A.3 // Arrange var key = CryptoBytes.FromHexString("1c9240a5eb55d38af333888604f6b5f0" + "473917c1402b80099dca5cbc207075c0"); var dat = CryptoBytes.FromHexString("2754776173206272696c6c69672c2061" + "6e642074686520736c6974687920746f" + "7665730a446964206779726520616e64" + "2067696d626c6520696e207468652077" + "6162653a0a416c6c206d696d73792077" + "6572652074686520626f726f676f7665" + "732c0a416e6420746865206d6f6d6520" + "7261746873206f757467726162652e"); // Act var mac = new byte[Poly1305.MAC_TAG_SIZE_IN_BYTES]; Poly1305.ComputeMac(key, dat, mac); // Assert mac.Should().Equal(CryptoBytes.FromHexString("4541669a7eaaee61e708dc7cbcc5eb62")); }
public void EncryptDecryptLongMessagesWithNonceTest() { var rnd = new Random(); var dataSize = 16; while (dataSize <= (1 << 24)) { var plaintext = new byte[dataSize]; rnd.NextBytes(plaintext); var key = new byte[Snuffle.KEY_SIZE_IN_BYTES]; rnd.NextBytes(key); var cipher = new ChaCha20(key, 0); var nonce = new byte[cipher.NonceSizeInBytes()]; rnd.NextBytes(nonce); var ciphertext = cipher.Encrypt(plaintext, nonce); var decrypted = cipher.Decrypt(ciphertext, nonce); //Assert.AreEqual(plaintext, decrypted); Assert.IsTrue(CryptoBytes.ConstantTimeEquals(plaintext, decrypted)); dataSize += 5 * dataSize / 11; } }
internal static string _Encode(byte[] privateKey, byte[] pubKey, string msg, byte[] iv, byte[] salt) { var shared = new byte[32]; Ed25519.key_derive( shared, salt, privateKey, pubKey); using (Aes aesAlg = Aes.Create()) { aesAlg.Key = shared; aesAlg.IV = iv; aesAlg.Mode = CipherMode.CBC; var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(msg); } return(CryptoBytes.ToHexStringLower(salt) + CryptoBytes.ToHexStringLower(iv) + CryptoBytes.ToHexStringLower(msEncrypt.ToArray())); } } } }
public void ChaCha20BlockTestVector() { // https://tools.ietf.org/html/rfc8439#section-2.3.2 // Arrange var key = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty)); var nonce = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00".Replace(":", string.Empty)); var counter = 1; // Act var chacha20 = new ChaCha20(key, 1); var output = new byte[ChaCha20.BLOCK_SIZE_IN_BYTES]; chacha20.ProcessKeyStreamBlock(nonce, counter, output); // Assert var expected = new uint[16] { 0xe4e7f110, 0x15593bd1, 0x1fdd0f50, 0xc47120a3, 0xc7f4d1c7, 0x0368c033, 0x9aaa2204, 0x4e6cd4c3, 0x466482d2, 0x09aa9f07, 0x05d7c214, 0xa2028bd9, 0xd19c12b5, 0xb94e16de, 0xe883d0cb, 0x4e3c50a2, }; output.ToUInt16Array().Should().Equal(expected); }
public static void CryptoSign( byte[] sig, int sigoffset, byte[] m, int moffset, int mlen, byte[] sk, int skoffset) { var hasher = new Sha512(); { hasher.Update(sk, skoffset, 32); var az = hasher.Finalize(); ScalarOperations.Clamp(az, 0); hasher.Init(); hasher.Update(az, 32, 32); hasher.Update(m, moffset, mlen); var r = hasher.Finalize(); ScalarOperations.Reduce(r); GroupElementP3 R; GroupOperations.ScalarMultBase(out R, r, 0); GroupOperations.P3ToBytes(sig, sigoffset, ref R); hasher.Init(); hasher.Update(sig, sigoffset, 32); hasher.Update(sk, skoffset + 32, 32); hasher.Update(m, moffset, mlen); var hram = hasher.Finalize(); ScalarOperations.Reduce(hram); var s = new byte[32]; Array.Copy(sig, sigoffset + 32, s, 0, 32); ScalarOperations.MulAdd(s, hram, az, r); Array.Copy(s, 0, sig, sigoffset + 32, 32); CryptoBytes.Wipe(s); } }
public void ConstantTimeEqualsSuccess() { var x = new byte[] { 1, 2, 3 }; var y = new byte[] { 1, 2, 3 }; Assert.IsTrue(CryptoBytes.ConstantTimeEquals(x, y)); }
public void ConstantTimeEqualsSegmentsMustHaveSameLength() { var x = new byte[5]; var y = new byte[5]; Assert.Throws <ArgumentException>(() => CryptoBytes.ConstantTimeEquals(new ArraySegment <byte>(x, 0, 4), new ArraySegment <byte>(y, 0, 5))); }
public void ConstantTimeEqualsSegmentsMustHaveSameLength() { var x = new byte[5]; var y = new byte[5]; CryptoBytes.ConstantTimeEquals(new ArraySegment <byte>(x, 0, 4), new ArraySegment <byte>(y, 0, 5)); }
/*public static void crypto_sign( * byte[] sm, out int smlen, * byte[] m, int mlen, * byte[] sk * ) * { * byte[] az = new byte[64]; * byte[] r = new byte[64]; * byte[] hram = new byte[64]; * GroupElementP3 R; * int i; * * Helpers.crypto_hash_sha512(az, sk, 0, 32); * az[0] &= 248; * az[31] &= 63; * az[31] |= 64; * * smlen = mlen + 64; * for (i = 0; i < mlen; ++i) sm[64 + i] = m[i]; * for (i = 0; i < 32; ++i) sm[32 + i] = az[32 + i]; * Helpers.crypto_hash_sha512(r, sm, 32, mlen + 32); * for (i = 0; i < 32; ++i) sm[32 + i] = sk[32 + i]; * * ScalarOperations.sc_reduce(r); * GroupOperations.ge_scalarmult_base(out R, r, 0); * GroupOperations.ge_p3_tobytes(sm, 0, ref R); * * Helpers.crypto_hash_sha512(hram, sm, 0, mlen + 64); * ScalarOperations.sc_reduce(hram); * var sm32 = new byte[32]; * Array.Copy(sm, 32, sm32, 0, 32); * ScalarOperations.sc_muladd(sm32, hram, az, r); * Array.Copy(sm32, 0, sm, 32, 32); * }*/ internal static void crypto_sign2(byte[] sig, int sigoffset, byte[] m, int moffset, int mlen, byte[] sk, int skoffset) { byte[] az; byte[] r; byte[] hram; var hasher = new Sha512(); { hasher.Update(sk, skoffset, 32); az = hasher.Finish(); ScalarOperations.sc_clamp(az, 0); hasher.Init(); hasher.Update(az, 32, 32); hasher.Update(m, moffset, mlen); r = hasher.Finish(); ScalarOperations.sc_reduce(r); GroupOperations.ge_scalarmult_base(out GroupElementP3 R, r, 0); GroupOperations.ge_p3_tobytes(sig, sigoffset, ref R); hasher.Init(); hasher.Update(sig, sigoffset, 32); hasher.Update(sk, skoffset + 32, 32); hasher.Update(m, moffset, mlen); hram = hasher.Finish(); ScalarOperations.sc_reduce(hram); var s = new byte[32]; // TODO: remove allocation Array.Copy(sig, sigoffset + 32, s, 0, 32); ScalarOperations.sc_muladd(s, hram, az, r); Array.Copy(s, 0, sig, sigoffset + 32, 32); CryptoBytes.Wipe(s); } }
private void Serialize() { var sumLen = 0; foreach (var p in MosaicProperties) { sumLen += p.PropertyLength + 4; } Length = 60 + NamespaceId.Length + MosaicName.Length + Description.Length + sumLen; // mosaic definition length if (Model.MosaicLevy != null) { Serializer.WriteInt(Length + (Model.MosaicLevy.Length - 4)); } else { Serializer.WriteInt(Length); } // length if creator public key Serializer.WriteInt(ByteLength.PublicKeyLength); // creator public key Serializer.WriteBytes(CryptoBytes.FromHexString(Creator.Raw)); // mosaic id structure length Serializer.WriteInt(ByteLength.EightBytes + NamespaceId.Length + MosaicName.Length); // namespace id length Serializer.WriteInt(NamespaceId.Length); // namespace Serializer.WriteBytes(NamespaceId); // mosaic name length Serializer.WriteInt(MosaicName.Length); // mosaic name Serializer.WriteBytes(MosaicName); // description length Serializer.WriteInt(Description.Length); // description Serializer.WriteBytes(Description); // properties count Serializer.WriteInt(MosaicProperties.Count); foreach (var mp in MosaicProperties) { Serializer.WriteBytes(mp.GetBytes()); } }
public static byte[] ExpandedPrivateKeyFromSeed(byte[] privateKeySeed) { byte[] privateKey; byte[] publicKey; KeyPairFromSeed(out publicKey, out privateKey, privateKeySeed); CryptoBytes.Wipe(publicKey); return(privateKey); }