base64的替代编码功能

时间:2012-07-28 13:37:44

标签: encoding

有没有人知道类似于base64_encode / decode的编码/解码功能,但只输出数字和/或字母,因为base64有时会输出=这会弄乱我的代码。谢谢

2 个答案:

答案 0 :(得分:1)

Base64不是加密。我建议你了解一下加密意味着什么。但无论如何,它听起来像你想要的是Base32编码。在Python中,您可以通过执行

来实现它
base64.b32encode(data)

编辑:默认情况下,base32编码也使用=来填充,但是如果它导致了问题,你可以简单地省略填充。

base64.b32encode(data).rstrip('=')

答案 1 :(得分:0)

这是我为我编写的owncloud app创建的算法。您可以指定自己的字母表,因此值得一试。实现是在PHP,但可以很容易地移植。

  /**
   * @method randomAlphabet
   * @brief Creates a random alphabet, unique but static for an installation
   * @access public
   * @author Christian Reiner
   */
  static function randomAlphabet ($length)
  {
    if ( ! is_integer($length) )
      return FALSE;
    $c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";
    return substr ( str_shuffle($c), 0, $length );
  } // function randomAlphabet

  /**
   * @method OC_Shorty_Tools::convertToAlphabet
   * @brief Converts a given decimal number into an arbitrary base (alphabet)
   * @param integer number: Decimal numeric value to be converted
   * @return string: Converted value in string notation
   * @access public
   * @author Christian Reiner
   */
  static function convertToAlphabet ( $number, $alphabet )
  {
    $alphabetLen = strlen($alphabet);
    if ( is_numeric($number) )
         $decVal = $number;
    else throw new OC_Shorty_Exception ( "non numerical timestamp value: '%1'", array($number) );
    $number = FALSE;
    $nslen = 0;
    $pos = 1;
    while ($decVal > 0)
    {
      $valPerChar = pow($alphabetLen, $pos);
      $curChar = floor($decVal / $valPerChar);
      if ($curChar >= $alphabetLen)
      {
        $pos++;
      } else {
        $decVal -= ($curChar * $valPerChar);
        if ($number === FALSE)
        {
          $number = str_repeat($alphabet{1}, $pos);
          $nslen = $pos;
        }
        $number = substr($number, 0, ($nslen - $pos)) . $alphabet{(int)$curChar} . substr($number, (($nslen - $pos) + 1));
        $pos--;
      }
    }
    if ($number === FALSE) $number = $alphabet{1};
    return $number;
  }