Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Use the Windows Crypto API for Base64 encoding/decoding

How To

Use the Windows Crypto API for Base64 encoding/decoding

by  Glenn9999  Posted    (Edited  )
For the unit that this code uses, see faq102-7423

Base64 encode

Code:
function StringToBase64(instr: string; Flags: dword): string;
var
  sz: dword;
begin
  CryptBinaryToStringA(pointer(instr), Length(instr), Flags, nil, sz);
  SetLength(result, sz);
  CryptBinaryToStringA(pointer(instr), Length(instr), Flags, pointer(result), sz);
end;

cstr := StringToBase64(instr, CRYPT_STRING_BASE64);

Base64 decode

Code:
function StringFromBase64(instr: string; Flags: dword): string;
var
  sz, skip: dword;
begin
  CryptStringToBinaryA(pointer(instr), Length(instr), Flags, nil, sz, skip,
             Flags);
  SetLength(result, sz);
  CryptStringToBinaryA(pointer(instr), Length(instr), Flags, pointer(result),
            sz, skip, Flags);
end;
cstr := StringFromBase64(cstr, CRYPT_STRING_BASE64);

Other flag values are in the wincrypt unit posted elsewhere.

Encoding a file into base64. I'm not sure if you can do this another way than using the API file mapping (TFileStream?), but this seems to be the best way to use the functions to do that.

Code:
procedure Base64EncFile(infilename, outfilename: string);
// copies file in infile to outfile.  Uses file mapping to read, but regular
// Delphi "file" to write.

var
  FileHandle: THandle;
  MapHandle: THandle;
  ViewPointer: Pointer;
  outptr: Pointer;
  outfile: file;
  outsize: longint;
begin
  FileHandle := CreateFile(Pchar(infilename), GENERIC_READ,
      FILE_SHARE_READ or FILE_SHARE_WRITE,nil, OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0);
  MapHandle := CreateFileMapping(FileHandle, nil, PAGE_READONLY, 0, 0, nil);
  ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, 0, 0, 0);
  if ViewPointer <> nil then
    try
      Assign(outfile, outfilename);
      rewrite(outfile, 1);
      CryptBinaryToStringA(ViewPointer, GetFileSize(FileHandle, nil),
                CRYPT_STRING_BASE64, nil, outsize);
      GetMem(outptr, outsize);
      CryptBinaryToStringA(ViewPointer, GetFileSize(FileHandle, nil),
                CRYPT_STRING_BASE64, outptr, outsize);
      BlockWrite(outfile, outptr^, outsize);
      Close(outfile);
      FreeMem(outptr);
    finally
      UnMapViewofFile(ViewPointer);
    end;
  CloseHandle(maphandle);
  CloseHandle(FileHandle);
end;
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top