GithubHelp home page GithubHelp logo

wiry.base32's Introduction

Wiry.Base32

NuGet License

Base32 and ZBase32 encoding and decoding library.

AppVeyor (Windows): AppVeyor

Travis CI (Linux & macOS): Travis CI

.NET compatibility:

  • .NET Framework (4.5+)
  • .NET Core (netstandard 1.1+)

Installation

To install Wiry.Base32, run the following command in the Package Manager Console

PM> Install-Package Wiry.Base32

Usage example

using System;
using System.Linq;
using System.Text;
using Wiry.Base32;

namespace Base32ConsoleApp
{
    public class Program
    {
        public static void Main()
        {
            // original text
            string text = "Hello, World!";
            Console.WriteLine($"Text: '{text}'");
            byte[] inputBytes = Encoding.ASCII.GetBytes(text);

            // Convert to RFC 4648 Base32 string
            string base32 = Base32Encoding.Standard.GetString(inputBytes);
            Console.WriteLine($"base32: '{base32}'");

            // Convert to z-base-32 string
            string zbase32 = Base32Encoding.ZBase32.GetString(inputBytes);
            Console.WriteLine($"z-base-32: '{zbase32}'");

            // Convert data back and check it
            byte[] decodedBase32 = Base32Encoding.Standard.ToBytes(base32);
            if (inputBytes.SequenceEqual(decodedBase32))
                Console.WriteLine("Convert back from base32 successfully!");

            byte[] decodedZBase32 = Base32Encoding.ZBase32.ToBytes(zbase32);
            if (inputBytes.SequenceEqual(decodedZBase32))
                Console.WriteLine("Convert back from z-base-32 successfully!");
        }
    }
}

Output:

Text: 'Hello, World!'
base32: 'JBSWY3DPFQQFO33SNRSCC==='
z-base-32: 'jb1sa5dxfoofq551pt1nn'
Convert back from base32 successfully!
Convert back from z-base-32 successfully!

Validation example

using System;
using Wiry.Base32;

namespace ValidateConsoleApp
{
    class Program
    {
        static void Main()
        {
            var standard = Base32Encoding.Standard;
            Console.WriteLine("S1) " + standard.Validate(null));
            Console.WriteLine("S2) " + standard.Validate("MZXW6YQ="));
            Console.WriteLine("S3) " + standard.Validate("MZ@W6YQ="));
            Console.WriteLine("S4) " + standard.Validate("MZXW6YQ=="));
            Console.WriteLine("S5) " + standard.Validate("========"));

            var zbase = Base32Encoding.ZBase32;
            Console.WriteLine("Z1) " + zbase.Validate(null));
            Console.WriteLine("Z2) " + zbase.Validate("gr3doqbw8radnqb3go"));
            Console.WriteLine("Z3) " + zbase.Validate("gr3doqbw8radnqb3goa"));
            Console.WriteLine("Z4) " + zbase.Validate("gr3doqbw!radnqb3go"));
        }
    }
}

Output:

S1) InvalidArguments
S2) Ok
S3) InvalidCharacter
S4) InvalidLength
S5) InvalidPadding
Z1) InvalidArguments
Z2) Ok
Z3) InvalidLength
Z4) InvalidCharacter

Benchmarks

Benchmark repository

Test configuration: Win10 x64 @ Intel Core 2 Quad Q9550.

Test 1: 1000000 repeats with 64 bytes of data:

Library (alphabetical order) Encoding Decoding
.NET Base64 (baseline) 202 ms 336 ms
Albireo.Base32 v1.0.1 822 ms 3627 ms
Base3264-UrlEncoder v1.0.2 2839 ms 43972 ms
SimpleBase v1.3.1 480 ms 673 ms
WallF.BaseNEncodings v1.0.0 587 ms 3342 ms
Wiry.Base32 v1.1.1 331 ms 388 ms

Test 2: random data size from 0 to 100 bytes (500 sessions by 20000 repeats):

Encode duration

Decode duration

References

License

Copyright (c) Dmitry Razumikhin, 2016-2018.

Licensed under the MIT License.

wiry.base32's People

Contributors

dmitry-ra avatar dlemstra avatar

Stargazers

Mike Adelson avatar Ivan Tikhonov avatar Alexey Mironov avatar  avatar Craig Edwards avatar Alexey Konstantinov avatar Tomas Kouba avatar Morten avatar David Taylor avatar Anders Wåglund avatar Olaf Kober avatar Ahmad avatar Marcus Wichelmann avatar Luca Poretti avatar Daniel Lerch avatar  avatar Renat F. avatar Alexander Minza avatar  avatar Nick Dicandia avatar  avatar  avatar Blake Scherschel avatar  avatar Matthew Little avatar Robert Campbell avatar Stefan Schälle avatar

Watchers

Anders Wåglund avatar James Cloos avatar  avatar  avatar

wiry.base32's Issues

Add method to verify input zbase32 string

Add a method to verify input zbase32 string. So ToBytes method will just work with "primary" and with "alias" values, but users can be able to check their data if they need.
More info: issue #2

change access modifier from internal to protected/public

Trying to create another base32 implementation other than the ones provided. However:

  1. Base32Encoding.ToBase32() has internal access modifier. Line 294
  2. Base32Encoding.GetOrCreateLookupTable() has internal access modifier. Line 83

Could you make those protected or public so that an inheriting class has access to those?

zbase32: decoding certain input fails

Example text: "gaaaaaaaa"

The exception is weird; I can't even "catch" it. While debugging, VS serves me the standard exception-info popup, after which my host-app simply crashes, without giving me a chance to step-through the catch block (and I can't easily/quickly write logging code to see if there's more information there). All I see is:

FatalExecutionEngineError occurred
Message: Managed Debugging Assistant 'FatalExecutionEngineError' has detected a problem in 'C:\Program Files\IIS Express\iisexpress.exe'.
Additional information: The runtime has encountered a fatal error. The address of the error was at 0x176b8ed0, on thread 0x62ac. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

I do understand that the input is likely bad, as I was appending "a" characters, one by one, to a valid "ga" zbase32-encoded text. Perhaps this is related. This is bad, as I can't even rely on error-handling code to determine bad input.

Nano custom alphabet encoding not giving correct result. Help?

Hey, so I'm trying to use the custom alphabet functionality of this lib since I'm trying to implement a Nano cryptocurrency client in CSharp. However for some reason I get the wrong encoding at the end, and since I'm too stupid to understand your code, I was hoping you could help me out?

Links for the nano stuff I'm using for reference:
https://docs.nano.org/integration-guides/the-basics/#seed (here the public address section)
https://docs.nano.org/integration-guides/key-management/

I get the byte array with this function:

  public static byte[] ConvertHexToByteArray(string hex)
  {
            return Enumerable.Range(0, hex.Length / 2).Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16))
                .ToArray();
  }

I have a test that checks for the string->byte array conversion so it should be okay. I'm trying to encode the public key to public address.
Key: 5b65b0e8173ee0802c2c3e6c9080d1a16b06de1176c938a924f58670904e82c4
Address: 1anrzcuwe64rwxzcco8dkhpyxpi8kd7zsjc1oeimpc3ppca4mrjt

Here is my code:

public byte[] PublicKey { get; private set; }

public string PublicAddress { get; private set; }

private static readonly CustomBase32Encoding Encoder = new CustomBase32Encoding("13456789abcdefghijkmnopqrstuwxyz", null);

public void GeneratePublicAddress()
{
    
    var blake2BConfig = new Blake2BConfig
    {
        OutputSizeInBytes = 5
    };
    var hasher = Blake2B.Create(blake2BConfig);
    hasher.Update(PublicKey, 0, 5);
    var digestHash = hasher.Finish();

   // The important stuff here:
    var base32Pub = Encoder.GetString(PublicKey);
    
    PublicAddress = "nano_"+base32Pub+Encoder.GetString(digestHash);
}

Thanks in advance :)

NU5125 licenseUrl error

Fix error NU5125: The 'licenseUrl' element will be deprecated. Consider using the 'license' element instead. on building.

z-base 32: potential bug: decoding inaccuracy

I'm not sure if I expect the library to do something that the algorithm doesn't support, but Wiry.Base32.Base32Encoding.ZBase32.ToBytes, given different values, produces exact same set of bytes. For example, this particular string, and any other that is comprised by the same and another character appended, produces the same set of bytes below.

base:
"gr3doqbw8radnqb3go"

other that produce same binary:
"gr3doqbw8radnqb3goa"
"gr3doqbw8radnqb3gob"
"gr3doqbw8radnqb3goc"
"gr3doqbw8radnqb3god"

{byte[11]}
[0]: 49
[1]: 50
[2]: 56
[3]: 56
[4]: 52
[5]: 57
[6]: 48
[7]: 49
[8]: 56
[9]: 57
[10]: 52

I guess, if the length of the encoded argument doesn't match the algorithm, I would expect an error, rather than trailing characters being ignored. This is very important to me, as I'm using these values as data identifiers, and while "gr3doqbw8radnqb3go" points to existing data record, I don't want to make it appear that ""gr3doqbw8radnqb3goa" is an alias to it. Please provide some guidance. If there is any work-around (e.g. my validating the length of the string using some formula, prior to feeding it to the 'ToBytes' method), please tell me.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.