Skip to content

Instantly share code, notes, and snippets.

@Earlz
Created October 15, 2014 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Earlz/9930890e1220cb7700e1 to your computer and use it in GitHub Desktop.
Save Earlz/9930890e1220cb7700e1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Base58ReverseEncoder
{
class Program
{
static void Main(string[] args)
{
var hash=new byte[160/8]; //in a normal address, this would be a ripemd160(publickey)
var bytes=new byte[160/8+1+4]; //include space for version byte and 4 checksum bytes
//hash is all 0 right now
hash.CopyTo(bytes, 1); //not necessary for our case, but just for illustration
bytes[0]=0x00; //VERSION NUMBER. Get this from base58.h or chainparams.cpp "pubkeyhash"
using(var sha256=new SHA256Managed())
{
var tmp = sha256.ComputeHash(sha256.ComputeHash(bytes.Take(160/8+1).ToArray())); //include verison number, but do not include leading 4 bytes where checksum will go
for (int i = 0; i < 4;i++)
{
//take 4 bytes and add them to the end of the address bytes. this is our checksum
bytes[bytes.Length - 4 + i] = tmp[i];
}
}
//base58 it up and it's all good
Console.WriteLine("Address: {0}", Base58Encode(bytes));
Console.ReadKey();
}
public static string Base58Encode(byte[] array)
{
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
string retString = string.Empty;
BigInteger encodeSize = ALPHABET.Length;
BigInteger arrayToInt = 0;
for (int i = 0; i < array.Length; ++i)
{
arrayToInt = arrayToInt * 256 + array[i];
}
while (arrayToInt > 0)
{
int rem = (int)(arrayToInt % encodeSize);
arrayToInt /= encodeSize;
retString = ALPHABET[rem] + retString;
}
for (int i = 0; i < array.Length && array[i] == 0; ++i)
retString = ALPHABET[0] + retString;
return retString;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment