Club Builder - Foros de discusión Club Builder
Foro de C++Builder en español
 
 FAQFAQ   BuscarBuscar   MiembrosMiembros   Grupos de UsuariosGrupos de Usuarios   RegistrarseRegistrarse 
 PerfilPerfil   Entra para ver tus mensajes privadosEntra para ver tus mensajes privados   EntrarEntrar 

Codificar y Decodificar Base64

 
Publicar nuevo tema   Responder al tema    Foros de discusión -> Consultas
Ver tema anterior :: Ver tema siguiente  
Autor Mensaje
Mensaje    Asunto: Codificar y Decodificar Base64 Responder citando

He visto en donde mediante incluir <memory> al proyecto pueden usar
TCOMIUtilities *util = CoUtilities::Create();

no obstante, me da error e indica que TComIUtilities no existe.

uso la version Rad Studio 10.1.

parecia facil pero no he dado con la libreria para poder usar el code y decode en base 64.

si alguien me ayuda en esto lo agradeceria enormemente
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: Responder citando

Este código es independiente de las librerías criptográficas de Windows:
Código:

typedef unsigned char BYTE;

char SB64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

int  IB64[] = {
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF, 0xFF, 0x3F,
    0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0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FF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

bool Decode64(char* S, BYTE* Bin, int *Count)
{
  if(!Bin && S){
    *Count = strlen(S)*3/4;
    return true;
  }

  if(!S || !Bin || *Count < strlen(S)*3/4) return false;

  BYTE B[4];
  int i = 0;
  int L = strlen(S);
  if(L < 4) return false;

  while(S[L] == '=') L--;
  *Count = (L*3)/4;

  int n = 1;
  do{
    for(int j = 0; j<4; j++){
      while(n < L && IB64[S[n]] == 0xFF) n++;
      B[j] = IB64[S[n]];
      n++;
    }
    Bin[i] =   (B[0] << 2) | (B[1] >> 4);
    if(B[2] == 255) break;
    Bin[i+1] = (B[1] << 4) | (B[2] >> 2);
    if(B[3] == 255) break;
    Bin[i+2] = (B[2] << 6) | B[3];
    i += 3;
  } while(n <= L);
  return true;
}

bool Encode64(BYTE* Bin, int Count, char* S, int *Size)
{
  BYTE B0, B1, B2;
  int n = 0;
  int i = 1;
  if(S == 0){
    *Size = ((Count+2) / 3)*4 + 1;
    return true;
  }

  if(Count == 0 || !Bin || *Size < ((Count+2) / 3)*4 + 1) return false;

  do{
    B0 = Bin[n];
    B1 = 0; B2 = 0;
    if (Count - n > 0) B1 = Bin[n+1];
    if (Count - n > 1) B2 = Bin[n+2];
    S[i] =   SB64[(B0 >> 2) & 0x3F];
    S[i+1] = SB64[((B0 << 4) | (B1 >> 4)) & 0x3F];
    S[i+2] = SB64[((B1 << 2) | (B2 >> 6)) & 0x3F];
    S[i+3] = SB64[(B2 & 0x3F)];
    n += 3;
    i += 4;
  } while(n < Count);
  if(n - Count >= 1) S[*Size-1] = '=';
  if(n - Count == 2) S[*Size-2] = '=';
  S[*Size] = 0;
  return true;
}

String Encode64(BYTE* Bin, int Count)
{
  String Result = "";
  BYTE B0, B1, B2;
  int n = 0;
  int i = 1;
  int L = ((Count+2) / 3)*4;

  Result.SetLength(L);

  if(Count == 0) return Result;
  do{
    B0 = Bin[n];
    B1 = 0; B2 = 0;
    if (Count - n > 0) B1 = Bin[n+1];
    if (Count - n > 1) B2 = Bin[n+2];
    Result[i] =   SB64[(B0 >> 2) & 0x3F];
    Result[i+1] = SB64[((B0 << 4) | (B1 >> 4)) & 0x3F];
    Result[i+2] = SB64[((B1 << 2) | (B2 >> 6)) & 0x3F];
    Result[i+3] = SB64[(B2 & 0x3F)];
    n += 3;
    i += 4;
  } while(n < Count);
  if(n - Count >= 1) Result[L] =   '=';
  if(n - Count == 2) Result[L-1] = '=';
  return Result;
}

void Decode64(String S, BYTE** Binary, int *Count)
{
  BYTE B[4];
  int i = 0;
  int L = S.Length();
  if(L < 4) return;
  while(S[L] == '=') L--;
  *Count = (L*3)/4;
  BYTE *Bin = new BYTE[*Count];

  int n = 1;
  do{
    for(int j = 0; j<4; j++){
      while(n < L && IB64[S[n]] == 0xFF) n++;
      B[j] = IB64[S[n]];
      n++;
    }
    Bin[i] =   (B[0] << 2) | (B[1] >> 4);
    if(B[2] == 255) break;
    Bin[i+1] = (B[1] << 4) | (B[2] >> 2);
    if(B[3] == 255) break;
    Bin[i+2] = (B[2] << 6) | B[3];
    i += 3;
  } while(n <= L);
  *Binary = Bin;
}

String StreamEncode64(TMemoryStream *MStream)
{
  char *S;
  int Size;
  if(Encode64((BYTE*)MStream->Memory, MStream->Size, 0, &Size)){
    S = new char[Size];
    Encode64((BYTE*)MStream->Memory, MStream->Size, S, &Size);
  }
  String Result = AnsiString(S, Size);
  delete [] S;
  return Result;
}

void StreamDecode64(String S, TMemoryStream *MStream)
{
  BYTE *Bytes = 0;
  int Count;
  if(Decode64(&S[1], Bytes, &Count)){
    Bytes = new BYTE[Count];
    Decode64(&S[1], Bytes, &Count);
  }
  MStream->Size = Count;
  memcpy(MStream->Memory, Bytes, Count);
  delete [] Bytes;
}


Más información aquí.

Este otro usa las librerías criptográficas de Windows:
Código:


//---------------------------------------------------------------------------
// Code64
typedef BOOL (WINAPI *pCryptBinaryToString)(const BYTE *pbBinary, DWORD cbBinary, DWORD dwFlags, LPTSTR pszString, DWORD *pcchString);
typedef BOOL (WINAPI *pCryptStringToBinary)(LPTSTR pszString, DWORD pcchString, DWORD dwFlags, BYTE *pbBinary, DWORD *cbBinary, DWORD *pdwSkip, DWORD *pdwFlags);
#define CRYPT_STRING_BASE64   0x00000001
#define CRYPT_STRING_HEX      0x00000004
#define CRYPT_STRING_HEXASCII 0x00000005
#define CRYPT_STRING_NOCRLF   0x40000000    // solo > Win XP
#define CRYPT_STRING_NOCR     0x80000000
//---------------------------------------------------------------------------
// Codifica un buffer binario con Encode64 en una cadena de caracteres
// Al final de la cadena coloca CR/LF: "\r\n" (0x0D/0x0A)
bool BinToStr(BYTE *Bin, DWORD BinSize, char* Str, DWORD *StrSize)
{
  HMODULE hLib = LoadLibrary("Crypt32.dll");
  if(!hLib) return false;

  pCryptBinaryToString CryptBinaryToString =
                      (pCryptBinaryToString)GetProcAddress(hLib, "CryptBinaryToStringA");
  DWORD Size;
  DWORD Flag = CRYPT_STRING_BASE64;
  bool Result = CryptBinaryToString(Bin, BinSize, Flag, 0 , &Size);

  if(!Str){
    if(Result) *StrSize = Size;
    return Result;
  }
  if(Size > *StrSize)
    return false;

  Result = CryptBinaryToString(Bin, BinSize, Flag, Str, StrSize);

  FreeLibrary(hLib);
  return Result;
}

//---------------------------------------------------------------------------
// Decodifica una cadena Encode64 a su binario original
bool StrToBin(char* Str, BYTE *Bin, DWORD *BinSize)
{
  HMODULE hLib = LoadLibrary("Crypt32.dll");
  if(!hLib) return false;

  pCryptStringToBinary CryptStringToBinary =
                      (pCryptStringToBinary)GetProcAddress(hLib, "CryptStringToBinaryA");
  DWORD Size;
  bool Result = CryptStringToBinary(Str, lstrlen(Str), CRYPT_STRING_BASE64, 0, &Size, 0, 0);
  if(!Bin){
    if(Result) *BinSize = Size;
    return Result;
  }
  if(Size > *BinSize)
    return false;

  Result = CryptStringToBinary(Str, lstrlen(Str), CRYPT_STRING_BASE64, Bin, BinSize, 0, 0);

  FreeLibrary(hLib);
  return Result;
}


Ambos están probados en Builder5.


Saludos.
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Re: Codificar y Decodificar Base64 Responder citando

jotny escribió:
He visto en donde mediante incluir <memory> al proyecto pueden usar
TCOMIUtilities *util = CoUtilities::Create();

no obstante, me da error e indica que TComIUtilities no existe.

uso la version Rad Studio 10.1.

parecia facil pero no he dado con la libreria para poder usar el code y decode en base 64.

si alguien me ayuda en esto lo agradeceria enormemente

TCOMIUtilities es parte de la librería CAPICOM, te faltaría el paso más importante que es importar la librería:

https://cppbuilder.es/viewtopic.php?t=12670&highlight=capicom

Si solo la vas a usar para trabajar con Base64 seguramente te será más útil alguna de las alternativas que te ha puesto escafandra.
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mensaje    Asunto: Que interesante el componente Responder citando

que interesante el componente Leo, estuve mirando y me servirá mucho para poder realizar facturas electronicas desde mi aplicacion ya que puedo ver los certificados inscritos.

que un detalle me abriera una puerta aun más amplia de lo que necesitaba.... muchas gracias Leo.
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: ocurre algo extraño cuando hago el encode Responder citando

Me ocurre algo extraño y espero sea algo tan simple como la guía que me dio leo_.

tengo el siguiente texto, declarado como UnicodeString

UnicodeString Mensaje="hola a todos en el foro, este mensaje sera convertido a base 64"

UnicodeString base64=util->Base64Encode(Mensaje.w_str());

el resultado me da lo siguiente al inspeccionar la conversion

aABvAGwAYQAgAGEAIAB0AG8AZABvAHMAIABlAG4AIABlAGwAIABmAG8AcgBvACwA
IABlAHMAdABlACAAbQBl


no obstante, al codificar en la pagina en linea https://www.base64encode.org/ me entrega algo muy diferente

aG9sYSBhIHRvZG9zIGVuIGVsIGZvcm8sIGVzdGUgbWVuc2FqZSBzZXJhIGNvbnZlcnRpZG8gYSBiYXNlIDY0

que error estaré cometiendo?.
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: Re: ocurre algo extraño cuando hago el encode Responder citando

jotny escribió:
Me ocurre algo extraño y espero sea algo tan simple como la guía que me dio leo_.

tengo el siguiente texto, declarado como UnicodeString

UnicodeString Mensaje="hola a todos en el foro, este mensaje sera convertido a base 64"

UnicodeString base64=util->Base64Encode(Mensaje.w_str());

el resultado me da lo siguiente al inspeccionar la conversion

aABvAGwAYQAgAGEAIAB0AG8AZABvAHMAIABlAG4AIABlAGwAIABmAG8AcgBvACwA
IABlAHMAdABlACAAbQBl


no obstante, al codificar en la pagina en linea https://www.base64encode.org/ me entrega algo muy diferente

aG9sYSBhIHRvZG9zIGVuIGVsIGZvcm8sIGVzdGUgbWVuc2FqZSBzZXJhIGNvbnZlcnRpZG8gYSBiYXNlIDY0

que error estaré cometiendo?.


El problema es el UNICODE, la pagina en linea https://www.base64encode.org/ trabaja con AnsiChar.

Si compilas el código que subí considerando que CHAR es AnsiChar y String es AnsiSsring, obtendrás el mismo resultado que en la web.

No lo he probado, pero tu código debe funcionar igual aplicando los mismos criterios.


Saludos.
Volver arriba
Ver perfil de usuario Enviar mensaje privado
Mostrar mensajes de anteriores:   
Cambiar a:  
No puedes publicar temas nuevos en este foro
No puedes responder a temas en este foro
No puedes editar tus mensajes en este foro
No puedes borrar tus mensajes en este foro
No puedes votar en las encuestas de este foro


Hosting WordPress Indedmedia desde 3,99 €
© 2002–2026 Club Builder · Funciona con phpBB.