C语言 如何对字符串进行 base58 编码


char (* text)[1][45+1];
text = calloc(5000,(130+1));
strcpy(0[*text],"sometext)");

现在我想将"sometext"编码为 base58,但是,我不知道如何,奇怪的是,C 中没有一个 BASE58 的例子。

我感兴趣的base58编码使用以下符号:

123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ

它已经过优化以降低误读的风险,例如,0 和"O"都消失了。

附言不要介意变量的奇怪分配和声明,我正在试验。

你不应该对

字符串进行编码,而应该对整数进行编码。

如果以字符串开头,则必须首先决定如何将其解释为整数(可能是 base128 或其他(,然后在 base58 中重新编码。

Satoshi 有参考实现 (https://github.com/bitcoin/bitcoin/blob/master/src/base58.h(

但是,他使用了一些实用程序 bignum 类来做到这一点,而且它C++。如果你可以访问一个 bignum 库,你只需继续除以 58,直到数字被分解。如果你没有一个bignum图书馆,AFAIK你运气不好。

这是我在 PHP 中为 Amithings 创建的大数字的实现,超出了整数(整数 -> http://php.net/manual/en/language.types.integer.php(。

例如,尝试下面的示例(不要忘记以字符串格式将您的 ID 传递给函数。使用 PHP 函数 strval(((:

$number = '123456789009876543211234567890';
$result = base58_encode($number);
echo('Encoded: ' . $result . '<br>');
echo('Decoded: ' . base58_decode($result) . '<br>');

重要事项: 您可以考虑通过包含某种密钥/密码/加密来更改此例程,以确保其他人无法解码您的数据库 ID。

function base58_encode($input)
{
    $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
    $base_count = strval(strlen($alphabet));
    $encoded = '';
    while (floatval($input) >= floatval($base_count))
    {
        $div = bcdiv($input, $base_count);
        $mod = bcmod($input, $base_count);
        $encoded = substr($alphabet, intval($mod), 1) . $encoded;
        $input = $div;
    }
    if (floatval($input) > 0)
    {
        $encoded = substr($alphabet, intval($input), 1) . $encoded;
    }
    return($encoded);
}
function base58_decode($input)
{
    $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
    $base_count = strval(strlen($alphabet));
    $decoded = strval(0);
    $multi = strval(1);
    while (strlen($input) > 0)
    {
        $digit = substr($input, strlen($input) - 1);
        $decoded = bcadd($decoded, bcmul($multi, strval(strpos($alphabet, $digit))));
        $multi = bcmul($multi, $base_count);
        $input = substr($input, 0, strlen($input) - 1);
    }
    return($decoded);
}

我使用 Crypto++ 库的简单代码:


  string base58_encode(Integer num, string vers)
  {
    string alphabet[58] = {"1","2","3","4","5","6","7","8","9","A","B","C","D","E","F",
    "G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c",
    "d","e","f","g","h","i","j","k","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    int base_count = 58; string encoded; Integer div; Integer mod;
    while (num >= base_count)
    {
        div = num / base_count;   mod = (num - (base_count * div));
        encoded = alphabet[ mod.ConvertToLong() ] + encoded;   num = div;
    }
    encoded = vers + alphabet[ num.ConvertToLong() ] + encoded;
    return encoded;
  }
It's just for cryptocurrency wallets. string can be changed for other tasks.

Here is an implementation that seems to be pure c.

https://github.com/trezor/trezor-crypto/blob/master/base58.c

相关内容

  • 没有找到相关文章

最新更新