Saltar al contenido

Decodificación Base32

Mantén la atención ya que en este artículo hallarás la contestación que buscas.Esta noticia fue analizado por nuestros especialistas para asegurar la calidad y veracidad de nuestro post.

Solución:

Necesitaba un codificador/descodificador base32, así que pasé un par de horas esta tarde armando esto. Creo que cumple con los estándares enumerados aquí: http://tools.ietf.org/html/rfc4648#section-6.

public class Base32Encoding

    public static byte[] ToBytes(string input)
    
        if (string.IsNullOrEmpty(input))
        
            throw new ArgumentNullException("input");
        

        input = input.TrimEnd('='); //remove padding characters
        int byteCount = input.Length * 5 / 8; //this must be TRUNCATED
        byte[] returnArray = new byte[byteCount];

        byte curByte = 0, bitsRemaining = 8;
        int mask = 0, arrayIndex = 0;

        foreach (char c in input)
        
            int cValue = CharToValue(c);

            if (bitsRemaining > 5)
             mask);
                bitsRemaining -= 5;
            
            else
            
                mask = cValue >> (5 - bitsRemaining);
                curByte = (byte)(curByte 
        

        //if we didn't end with a full byte
        if (arrayIndex != byteCount)
        
            returnArray[arrayIndex] = curByte;
        

        return returnArray;
    

    public static string ToString(byte[] input)
    

    private static int CharToValue(char c)
    
        int value = (int)c;

        //65-90 == uppercase letters
        if (value < 91 && value > 64)
        
            return value - 65;
        
        //50-55 == numbers 2-7
        if (value < 56 && value > 49)
        
            return value - 24;
        
        //97-122 == lowercase letters
        if (value < 123 && value > 96)
        
            return value - 97;
        

        throw new ArgumentException("Character is not a Base32 character.", "c");
    

    private static char ValueToChar(byte b)
    
        if (b < 26)
        
            return (char)(b + 65);
        

        if (b < 32)
        
            return (char)(b + 24);
        

        throw new ArgumentException("Byte is not a value Base32 value.", "b");
    


Mira esto FromBase32String implementación para .NET que se encuentra aquí.


Editar: el enlace anterior estaba muerto; puede encontrar una copia archivada en archive.org

El código real decía:

using System;
using System.Text;

public sealed class Base32 

      // the valid chars for the encoding
      private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";

      /// 
      /// Converts an array of bytes to a Base32-k string.
      /// 
      public static string ToBase32String(byte[] bytes) 
            StringBuilder sb = new StringBuilder();         // holds the base32 chars
            byte index;
            int hi = 5;
            int currentByte = 0;

            while (currentByte < bytes.Length) 
                  // do we need to use the next byte?
                  if (hi > 8) 
                        // get the last piece from the current byte, shift it to the right
                        // and increment the byte counter
                        index = (byte)(bytes[currentByte++] >> (hi - 5));
                        if (currentByte != bytes.Length)  index);
                        

                        hi -= 3;
                   else if(hi == 8)  
                        index = (byte)(bytes[currentByte++] >> 3);
                        hi -= 3; 
                   else 

                        // simply get the stuff from the current byte
                        index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
                        hi += 5;
                  

                  sb.Append(ValidChars[index]);
            

            return sb.ToString();
      


      /// 
      /// Converts a Base32-k string into an array of bytes.
      /// 
      /// 
      /// Input string s contains invalid Base32-k characters.
      /// 
      public static byte[] FromBase32String(string str) 
            int numBytes = str.Length * 5 / 8;
            byte[] bytes = new Byte[numBytes];

            // all UPPERCASE chars
            str = str.ToUpper();

            int bit_buffer;
            int currentCharIndex;
            int bits_in_buffer;

            if (str.Length < 3)  ValidChars.IndexOf(str[1]) << 5);
                  return bytes;
            

            bit_buffer = (ValidChars.IndexOf(str[0]) 

Esta es una pregunta muy antigua, pero me topé con ella queriendo lo mismo para los tokens OTP. Resulta que hay una funcionalidad base 32 integrada en el paquete OTP.NET en NuGet:

Base32Encoding.ToBytes("(your base 32 string here)")

También es posible lo contrario:

Base32Encoding.ToString(new byte[]  /* your bytes here */ )

Si aceptas, tienes el poder dejar una división acerca de qué te ha parecido esta reseña.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *