public void Sha512Stream_OneMillionSmallAs() { var(data, expected) = TestVectorsStream["Sha512-Stream One Million As"]; var hash = Sha512.Hash(data); CustomAssert.MatchArrays(hash, expected); }
public void Sha512Abc() { var message = new[] { (byte)'a', (byte)'b', (byte)'c' }; var hashExpected = _sha512HashAbc; var hash = Sha512.Hash(message); TestHelpers.AssertEqualBytes(hashExpected, hash); }
public void Sha512Stream_EmptyString() { var(data, expected) = TestVectorsStream["Sha512-Stream Empty String"]; var hash = Sha512.Hash(data); CustomAssert.MatchArrays(hash, expected); }
public void Sha512Stream_896Bits() { var(data, expected) = TestVectorsStream["Sha512-Stream 896 Bits"]; var hash = Sha512.Hash(data); CustomAssert.MatchArrays(hash, expected); }
public void Sha512_448Bits() { var(data, expected) = TestVectors["Sha512 448 Bits"]; var hash = Sha512.Hash(data); CustomAssert.MatchArrays(hash, expected); }
public static void Main() { const int n = 10000; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Console.WriteLine("Architecture: {0} bit", IntPtr.Size * 8); Console.WriteLine("CPU-Frequency: {0} MHz", Cpu.CpuFreq); Cpu.Setup(); Console.WriteLine(); Console.ReadKey(); var m = new byte[100]; var seed = new byte[32]; byte[] privateKey; byte[] publicKey; Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed); var sig = Ed25519.Sign(m, privateKey); Ed25519.Sign(m, privateKey); if (!Ed25519.Verify(sig, m, publicKey)) { throw new Exception("Bug"); } if (Ed25519.Verify(sig, m.Concat(new byte[] { 1 }).ToArray(), publicKey)) { throw new Exception("Bug"); } Console.BackgroundColor = ConsoleColor.Black; { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=== Edwards ==="); Benchmark("KeyGen", () => Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed), n); Benchmark("Sign", () => Ed25519.Sign(m, privateKey), n); Benchmark("Verify", () => Ed25519.Verify(sig, m, publicKey), n); Console.WriteLine(); } foreach (var size in new[] { 144, 1000, 2048 }) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=== Symmetric ({0}) ===", SizeToString(size)); var message = new byte[size]; var ciphertext = new byte[message.Length + 16]; var key = new byte[32]; var nonce = new byte[24]; Benchmark("SHA512Managed", () => new SHA512Managed().ComputeHash(message), n, size); Benchmark("SHA512Cng", () => new SHA512Cng().ComputeHash(message), n, size); Benchmark("SHA512CSP", () => new SHA512CryptoServiceProvider().ComputeHash(message), n, size); Benchmark("SHA512Chaos", () => Sha512.Hash(message), n, size); } Console.ReadLine(); }
public static void HashEmpty() { var a = new Sha512(); var expected = s_hashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan <byte> .Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); }
public static void HashEmptyWithSpan(int hashSize) { var a = new Sha512(); var expected = s_hashOfEmpty.DecodeHex().Substring(0, hashSize); var actual = new byte[hashSize]; a.Hash(ReadOnlySpan <byte> .Empty, actual); Assert.Equal(expected, actual); }
public static void Test(string msg, string digest) { var a = new Sha512(); var m = msg.DecodeHex(); var expected = digest.DecodeHex(); var actual = a.Hash(m, expected.Length); Assert.Equal(expected, actual); }
public static void crypto_sign_keypair(Span <byte> pk, Span <byte> sk, ReadOnlySpan <byte> seed) { Sha512.Hash(seed, sk); ScalarOperations.sc_clamp(sk); GroupOperations.ge_scalarmult_base(out var A, sk.Slice(0, 32)); GroupOperations.ge_p3_tobytes(pk, in A); seed.CopyTo(sk); pk.CopyTo(sk.Slice(32, 32)); }
public void Sha512_1() { var sha512Framework = new SHA512Managed(); for (int n = 0; n < 1000; n++) { var message = Enumerable.Range(1, n).Select(i => (byte)i).ToArray(); var hashExpected = sha512Framework.ComputeHash(message); var hash = Sha512.Hash(message); TestHelpers.AssertEqualBytes(hashExpected, hash); } }
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); 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 \
public void KeyExchange() { var seed = new byte[32]; byte[] publicEdwards, privateEdwards; Ed25519.KeyPairFromSeed(out publicEdwards, out privateEdwards, seed); var sharedEdwards = Ed25519.KeyExchange(publicEdwards, privateEdwards); var privateMontgomery = Sha512.Hash(seed).Take(32).ToArray(); var publicMontgomery = MontgomeryCurve25519.GetPublicKey(privateMontgomery); var sharedMontgomery = MontgomeryCurve25519.KeyExchange(publicMontgomery, privateMontgomery); TestHelpers.AssertEqualBytes(sharedMontgomery, sharedEdwards); }
public void KeyExchangeSegments() { var seed = new byte[32].Pad(); var publicEdwards = new byte[32].Pad(); var privateEdwards = new byte[64].Pad(); Ed25519.KeyPairFromSeed(publicEdwards, privateEdwards, seed); var sharedEdwards = new byte[32].Pad(); Ed25519.KeyExchange(sharedEdwards, publicEdwards, privateEdwards); var privateMontgomery = Sha512.Hash(seed.UnPad()).Take(32).ToArray(); var publicMontgomery = MontgomeryCurve25519.GetPublicKey(privateMontgomery); var sharedMontgomery = MontgomeryCurve25519.KeyExchange(publicMontgomery, privateMontgomery); TestHelpers.AssertEqualBytes(sharedMontgomery, sharedEdwards.UnPad()); }
internal 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); 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 static void CryptoSignKeypair(byte[] pk, int pkoffset, byte[] sk, int skoffset, byte[] seed, int seedoffset) { int i; Array.Copy(seed, seedoffset, sk, skoffset, 32); byte[] h = Sha512.Hash(sk, skoffset, 32); //ToDo: Remove alloc ScalarOperations.ScClamp(h, 0); GroupOperations.GeScalarmultBase(out GroupElementP3 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 static void CryptoSignKeyPair(byte[] pk, int pkoffset, byte[] sk, int skoffset, byte[] seed, int seedoffset) { int i; Array.Copy(seed, seedoffset, sk, skoffset, 32); var h = Sha512.Hash(sk, skoffset, 32); ScalarOperations.Clamp(h, 0); GroupOperations.ScalarMultBase(out var A, h, 0); GroupOperations.P3ToBytes(pk, pkoffset, ref A); for (i = 0; i < 32; ++i) { sk[skoffset + 32 + i] = pk[pkoffset + i]; } CryptoBytes.Wipe(h); }
public static void CryptoSignKeypair(byte[] pk, int pkoffset, byte[] sk, int skoffset, byte[] seed, int seedoffset) { int i; Array.Copy(seed, seedoffset, sk, skoffset, 32); var h = Sha512.Hash(sk, skoffset, 32); //ToDo: Remove alloc ScalarOperations.ScClamp(h, 0); stellar_dotnet_sdk.chaos.nacl.Internal.Ed25519Ref10.GroupOperations.GeScalarmultBase(out var a, h, 0); stellar_dotnet_sdk.chaos.nacl.Internal.Ed25519Ref10.GroupOperations.ge_p3_tobytes(pk, pkoffset, ref a); for (i = 0; i < 32; ++i) { sk[skoffset + 32 + i] = pk[pkoffset + i]; } CryptoBytes.Wipe(h); }
static void Main(string[] args) { Regex sign_matcher = new Regex(@"--sign=.*", RegexOptions.Compiled | RegexOptions.ECMAScript); Regex key_matcher = new Regex(@"--key=.*", RegexOptions.Compiled | RegexOptions.ECMAScript); Regex version_matcher = new Regex(@"--version=.*", RegexOptions.Compiled | RegexOptions.ECMAScript); Regex verify_matcher = new Regex(@"--verify=.*", RegexOptions.Compiled | RegexOptions.ECMAScript); Regex signature_matcher = new Regex(@"--signature=.*", RegexOptions.Compiled | RegexOptions.ECMAScript); if (args.Any(s => s == "--help")) { string executable_name = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) switch { true => "gms.exe", _ => "./gms" }; Console.WriteLine("GmodNetModuleSigner 1.0.0 by Gleb Krasilich. https://github.com/GlebChili/GmodNetModuleSigner."); Console.WriteLine("Usage: " + executable_name + " [FLAG1] [FLAG2] ...\n"); Console.WriteLine("Flags:\n"); Console.WriteLine("--help: usage help\n"); Console.WriteLine("--generate-key: Generate new private and public keys pair and save it as private.modulekey file.\n"); Console.WriteLine("--sign=[module_to_sign_path]: sign given file (relative or absolute path). Must be used wtih --key flag " + "and --version flag. Output: signature.modulesign file.\n"); Console.WriteLine("--key=[path_to_key]: Use following key for sign and verification process (relative or absolute path).\n"); Console.WriteLine("--version=[module_version]: Explicitly specify module version to add to *.modulekey file.\n"); Console.WriteLine("--verify=[module_to_verify_path]: Verify signature of the module. Must be used with --key and --signature flags."); Console.WriteLine("--signature=[path_to_the_signature_file]: Signature for the verification process."); } else if (args.Any(s => s == "--generate-key")) { Console.WriteLine("Generating new key pair"); Task <TextKeyPair> future_key = Task <TextKeyPair> .Factory.StartNew(GenerateKey, TaskCreationOptions.LongRunning); int tick_counter = 0; while (!future_key.IsCompleted) { tick_counter++; tick_counter = tick_counter % 1000000000; if (tick_counter == 0) { Console.Write("."); } } Console.Write("\n"); TextKeyPair result = future_key.Result; byte[] key_json = JsonSerializer.SerializeToUtf8Bytes <TextKeyPair>(result, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllBytes("private.modulekey", key_json); Console.WriteLine("Key pair generated and saved as private.modulekey file. KEEP YOUR SECRET KEY SAFE!"); } else if (args.Any(s => sign_matcher.IsMatch(s))) { Console.WriteLine("Starting sign process..."); string sign_flag = args.First(s => sign_matcher.IsMatch(s)); string sign_path; try { sign_path = sign_flag.Split("=")[1]; } catch { Console.WriteLine("Path for file to sign is empty or invalid. Try again."); return; } string key_flag = args.First(s => key_matcher.IsMatch(s)); string key_path; if (key_flag == null || key_flag == String.Empty) { Console.WriteLine("The --key=[path_to_key] flag is missing. Try again."); return; } try { key_path = key_flag.Split("=")[1]; } catch { Console.WriteLine("Key file path is empty or invalid. Try again."); return; } byte[] key_blob; try { key_blob = File.ReadAllBytes(key_path); } catch (Exception e) { Console.WriteLine("Unable to read key file: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } TextKeyPair key_pair; try { key_pair = JsonSerializer.Deserialize <TextKeyPair>(key_blob); } catch (Exception e) { Console.WriteLine("Unable to parse key file: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } if (key_pair.PrivateKey == null || key_pair.PrivateKey == String.Empty) { Console.WriteLine("The key file contains no secret key. Try again."); return; } string version_flag = args.First(s => version_matcher.IsMatch(s)); if (version_flag == null || version_flag == String.Empty) { Console.WriteLine("--version flag is missing. Try again."); return; } string version_name; try { version_name = version_flag.Split("=")[1]; } catch { Console.WriteLine("The vesrsion is empty or invalid. Try again."); return; } Sha512 sha512 = HashAlgorithm.Sha512; byte[] file_blob; try { file_blob = File.ReadAllBytes(sign_path); } catch (Exception e) { Console.WriteLine("Unable to read file to sign: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } byte[] file_hash = sha512.Hash(file_blob); file_hash = file_hash.Concat(Encoding.UTF8.GetBytes(version_name)).ToArray(); byte[] final_hash = sha512.Hash(file_hash); byte[] raw_private_key = HexToBytes(key_pair.PrivateKey); Ed25519 ed25519 = SignatureAlgorithm.Ed25519; Key private_key; try { private_key = Key.Import(ed25519, raw_private_key, KeyBlobFormat.RawPrivateKey); } catch (Exception e) { Console.WriteLine("Unable to import private key: " + e.GetType() + " " + e.Message + ". Try again."); return; } byte[] final_signature = ed25519.Sign(private_key, final_hash); ModuleSignature sign_struct = new ModuleSignature { Version = version_name, Signature = BitConverter.ToString(final_signature).Replace("-", "") }; byte[] sign_to_write = JsonSerializer.SerializeToUtf8Bytes <ModuleSignature>(sign_struct, new JsonSerializerOptions { WriteIndented = true }); File.WriteAllBytes("signature.modulesign", sign_to_write); Console.WriteLine("File was successfully signed."); } else if (args.Any(s => verify_matcher.IsMatch(s))) { Console.WriteLine("Starting verification process..."); string verify_flag = args.First(s => verify_matcher.IsMatch(s)); string verify_path; try { verify_path = verify_flag.Split("=")[1]; } catch { Console.WriteLine("Path for the file to verify is empty or invalid. Try again."); return; } string key_flag = args.First(s => key_matcher.IsMatch(s)); string key_path; if (key_flag == null || key_flag == String.Empty) { Console.WriteLine("The --key=[path_to_key] flag is missing. Try again."); return; } try { key_path = key_flag.Split("=")[1]; } catch { Console.WriteLine("Key file path is empty or invalid. Try again."); return; } string signature_flag = args.First(s => signature_matcher.IsMatch(s)); string signature_path; if (signature_flag == null || signature_flag == String.Empty) { Console.WriteLine("-signature=[path_to_the_signature] flag is missing. Try again."); return; } try { signature_path = signature_flag.Split("=")[1]; } catch { Console.WriteLine("Signature path is empty or invalid. Try again."); return; } byte[] file_blob; try { file_blob = File.ReadAllBytes(verify_path); } catch (Exception e) { Console.WriteLine("Unable to read the module to verify: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } byte[] key_blob; try { key_blob = File.ReadAllBytes(key_path); } catch (Exception e) { Console.WriteLine("Unable to read key: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } byte[] signature_blob; try { signature_blob = File.ReadAllBytes(signature_path); } catch (Exception e) { Console.WriteLine("Unable to read signature: " + e.GetType() + " " + e.Message + ". Try again."); return; } TextKeyPair key_pair; try { key_pair = JsonSerializer.Deserialize <TextKeyPair>(key_blob); } catch (Exception e) { Console.WriteLine("Unable to parse key file: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } if (key_pair.PublicKey == null || key_pair.PublicKey == String.Empty) { Console.WriteLine("Public key is empty or invalid. Try again."); return; } ModuleSignature signature; try { signature = JsonSerializer.Deserialize <ModuleSignature>(signature_blob); } catch (Exception e) { Console.WriteLine("Unable to parse signature file: " + e.GetType().ToString() + e.Message + ". Try again."); return; } Sha512 sha512 = HashAlgorithm.Sha512; byte[] file_hash = sha512.Hash(file_blob); file_hash = file_hash.Concat(Encoding.UTF8.GetBytes(signature.Version)).ToArray(); byte[] final_hash = sha512.Hash(file_hash); Ed25519 ed25519 = SignatureAlgorithm.Ed25519; PublicKey public_key; try { byte[] raw_public_key = HexToBytes(key_pair.PublicKey); public_key = PublicKey.Import(ed25519, raw_public_key, KeyBlobFormat.RawPublicKey); } catch (Exception e) { Console.WriteLine("Unable to parse public key: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } try { bool is_valid = ed25519.Verify(public_key, final_hash, HexToBytes(signature.Signature)); if (is_valid) { Console.WriteLine("Signature is valid."); } else { Console.WriteLine("Signature is NOT valid."); } } catch (Exception e) { Console.WriteLine("Unable to verify signature: " + e.GetType().ToString() + " " + e.Message + ". Try again."); return; } } else { Console.WriteLine("GmodNetModuleSigner 1.0.0 by Gleb Krasilich. https://github.com/GlebChili/GmodNetModuleSigner."); Console.WriteLine("Use --help flag for usage help."); } }
public static bool sendUpdateRequest(Image_t image, UDPServer server) { byte[] buffer = new byte[image.imgSize + 1000]; // hash the image byte[] hash = Sha512.Hash(image.img, 0, image.imgSize); var seed = new byte[32]; // empty seed byte[] pk, sk; Ed25519.KeyPairFromSeed(out pk, out sk, seed); int offset = 0; UInt32 processId = image.processId; UInt32 version = image.version; UInt32 start_disk_addr = image.start_disk_addr, start_cpio_addr = image.start_cpio_addr; // Data that should be signed.... : For now - Start-Disk-Addr || Start-Cpio-Addr || Version || Img Size || Process ID || hash int metadataLen = sizeof(int) * 5; int sigDataLen = hash.Length + metadataLen; byte[] sigData = new byte[sigDataLen]; Buffer.BlockCopy(BitConverter.GetBytes(start_disk_addr), 0, sigData, offset, 4); offset += 4; Buffer.BlockCopy(BitConverter.GetBytes(start_cpio_addr), 0, sigData, offset, 4); offset += 4; Buffer.BlockCopy(BitConverter.GetBytes(version), 0, sigData, offset, 4); offset += 4; Buffer.BlockCopy(BitConverter.GetBytes(image.imgSize), 0, sigData, offset, 4); offset += 4; Buffer.BlockCopy(BitConverter.GetBytes(processId), 0, sigData, offset, 4); offset += 4; Buffer.BlockCopy(hash, 0, sigData, offset, hash.Length); offset += hash.Length; byte[] sig = Ed25519.Sign(sigData, sk); // Update Request : MAC(32) || (Timestamp ||) SigData(84) // (|| PK Cert || Expire || Hash/SigAlg) || Hash(Img)(64) || Signature(64) || Public Key(32) offset = 0; Buffer.BlockCopy(sigData, 0, buffer, offset, sigDataLen); offset += sigDataLen; Buffer.BlockCopy(sig, 0, buffer, offset, sig.Length); //Console.WriteLine("Sig: " + BitConverter.ToString(sig)); offset += sig.Length; Buffer.BlockCopy(pk, 0, buffer, offset, pk.Length); //Console.WriteLine("PK: " + BitConverter.ToString(pk)); offset += pk.Length; int bufferSize = offset; //Console.WriteLine("Mac Data: " + BitConverter.ToString(buffer, 0, bufferSize) + " Len: "+bufferSize); // get MAC from LocalIPC server.LocalSend(buffer, bufferSize); byte[] mac = server.LocalReceive(); if (mac.Length != 32) { Console.WriteLine("sth is wrong"); } byte[] updateRequest = new byte[mac.Length + bufferSize]; offset = 0; Buffer.BlockCopy(mac, 0, updateRequest, 0, mac.Length); offset += mac.Length; Buffer.BlockCopy(buffer, 0, updateRequest, offset, bufferSize); offset += bufferSize; int requestSize = offset; server.Send(updateRequest, requestSize, UDPServer.SERVER_UPDATE_PORT, UDPServer.CLIENT_UPDATE_PORT); return(true); /*byte[] recv = server.Receive(UDPServer.SERVER_UPDATE_PORT); * // TODO: what is the best way to handle packet drops/losses? * if (recv == null) * { * return false; * } * return true;*/ }
public static void crypto_secret_key_from_seed(byte[] sk, int skoffset, byte[] seed, int seedoffset) { byte[] h = Sha512.Hash(seed, seedoffset, 32); //ToDo: Remove alloc ScalarOperations.sc_clamp(h, 0); Array.Copy(h, 0, sk, skoffset, 32); }