Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ARoomWithABue/93cf3b365cd9399795a79a09080eaed4 to your computer and use it in GitHub Desktop.
Save ARoomWithABue/93cf3b365cd9399795a79a09080eaed4 to your computer and use it in GitHub Desktop.
DSA Verification
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cryptography.ECDSA;
using System.Threading.Tasks;
namespace CryptoSandbox
{
class Program
{
public static readonly int PUB_KEY_DATA_SIZE = 33;
public static readonly int PRIV_KEY_DATA_SIZE = 32;
public static readonly int SIGN_KEY_DATA_SIZE = 64;
public static byte[] SignStringToBytes(string sign)
{
if (sign.StartsWith("SIG_K1_"))
return StringToKey(sign.Substring(7), SIGN_KEY_DATA_SIZE, "K1");
if (sign.StartsWith("SIG_R1_"))
return StringToKey(sign.Substring(7), SIGN_KEY_DATA_SIZE, "R1");
else
throw new Exception("unrecognized signature format.");
}
public static byte[] Combine(IEnumerable<byte[]> arrays)
{
byte[] ret = new byte[arrays.Sum(x => x != null ? x.Length : 0)];
int offset = 0;
foreach (byte[] data in arrays)
{
if (data == null) continue;
Buffer.BlockCopy(data, 0, ret, offset, data.Length);
offset += data.Length;
}
return ret;
}
public static byte[] StringToKey(string key, int size, string keyType = null)
{
byte[] keyBytes = Base58.Decode(key);
byte[] digest = null;
int versionSize = 0;
if (keyType == "sha256x2")
{
versionSize = 1;
digest = Sha256Manager.GetHash(Sha256Manager.GetHash(keyBytes.Take(size + versionSize).ToArray()));
}
else if (!string.IsNullOrWhiteSpace(keyType))
{
digest = Ripemd160Manager.GetHash(Combine(new List<byte[]>() {
keyBytes.Take(size).ToArray(),
Encoding.UTF8.GetBytes(keyType)
}));
}
else
{
digest = Ripemd160Manager.GetHash(keyBytes.Take(size).ToArray());
}
Console.WriteLine("digest.Length: " + digest.Length);
Console.Write("digest: ");
PrintBytes(digest);
Console.WriteLine("keyBytes.Length: " + keyBytes.Length);
Console.Write("keyBytes: ");
PrintBytes(keyBytes);
Console.Write("Checksum left: ");
PrintBytes(keyBytes.Skip(size + versionSize));
Console.Write("Checksum right: ");
PrintBytes(digest.Take(4));
if (!keyBytes.Skip(size + versionSize).SequenceEqual(digest.Take(4)))
{
throw new Exception("checksum doesn't match.");
}
return keyBytes;
}
public static void PrintBytes(IEnumerable<byte> arr)
{
var set = arr.ToArray<byte>();
for (int i = 0; i < set.Count(); i++)
{
if (i == 0)
Console.Write("[ ");
Console.Write(set[i]);
if (i == set.Length - 1)
Console.Write(" ]\n");
else
Console.Write(", ");
}
}
static void Main(string[] args)
{
var sig = "SIG_K1_KZoEShDrNxiAQq8rYafahdudAESBAfHQxU7ihavonMDMND4jNSHhk9q4UVbs7tTLK6RidFmFmSruipEM1chyxFgN46meSF";
//StringToKey(sig.Substring(7), SIGN_KEY_DATA_SIZE);
SignStringToBytes(sig);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment