Visual Basic 6

base64/MIME-Kodierung mit VB

Vereinheitlichen eines Strings auf einen reduzierten Zeichensatz

Möchte man einen größeren Text z.B. mit dem ZIP-Algorithmus "eindampfen" steht man zunächst vor dem Problem, dass dieser keine Sonderzeichen verarbeiten kann. Die in Deutschland so beliebten Umlaute und andere Sonderzeichen sind schlichtweg Tabu. Da hilft nur eine Kodierung und zwar mit dem sog. base64-Algorithmus, auch MIME-Kodierung genannt. Entwickelt wurde dieser im Zuge ursprünglich, um den Text von eMails zu vereinheitlichen, um Datenverluste durch unterschiedliche Zeichensätze zu vermeiden. Die meisten eMail-Anhänge werden bis heute nach diesem Verfahren codiert.

Grundlage der base64-Kodierung ist ein reduzierter Zeichensatz mit 64 Zeichen, der in allen Zeichensätzen vorkommt:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

Diese 64 Zeichen entsprechen genau 6 Bits (64 = 26), daher wird der Datenstrom eines Textes (z.B. "Test"), der 4 Zeichen (Bytes) mit 8 Bits enthält, in 6-Bit-Häppchen zerlegt. Drei Bytes des Textes ergeben 4 Bytes der Kodierung, d.h. die Byte-Länge des Textes muss durch drei teilbar sein. Ist sie das nicht, d.h. die Aufteilung in 6er-Gruppen geht nicht auf (2 oder 4 Bits fehlen) wird mit Nullen aufgefüllt.

Diese 6-Bitmustern werden anschließend Zeichen aus dem ASCII-Zeichensatz zugeordnet. Die am Ende des neuen Strings aufgrund der angehängten Nullen entstandenen Buchstaben 'A' werden durch das Zeichen '=' ersetzt, dass in base64 als Füllzeichen gilt.

Obwohl jedes dieser ASCII-Zeichen nur 6 Bit darstellt, hat es jedoch weiterhin einen Speicherbedarf von 8 Bit. Aus diesem Grunde ist ein base64-kodierter Text auch 30% länger als der Quelltext.

Schema

Zeichen T e s t [Füllz.] [Füllz.] [Füllz.] [Füllz.]
ASCII-Code 84 101 115 116        
binär (8 Bit) 01010100 01100101 01110011 01110100 00000000 00000000    
6 Bit-Gruppe 010101 000110 010101 110011 011101 000000 000000 000000
dezimal 86 71 86 90 100 0 0 0
Zeichen V G V z d = = =

Kodieren

Public Function EncodeBase64(strInput As String) As String

   Dim arrChars64() As Byte
   Dim arrInput() As Byte
   Dim arrOutput() As Byte
   Dim arrByte(3) As Integer
   Dim arrChar(4) As Integer
   Dim intLen As Integer
   Dim intDelta As Integer
   Dim i As Long
   Dim j As Long
   
   Const cstrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
      
   'Zeichentabelle in Byte-Array ablegen
   arrChars64() = StrConv(cstrBase64, vbFromUnicode)
   
   'Länge ermitteln und prüfen
   intLen = Len(strInput)
   If intLen = 0 Then Exit Function

   'Input in Byte-Array ablegen
   arrInput() = StrConv(strInput, vbFromUnicode)
   
   'Wenn Input nicht glatt durch 3 teilbar...
   intDelta = intLen Mod 3
   If intDelta > 0 Then
      '...Input-Array auf die nächste durch 3 teilbare Zahl erweitern
      intLen = ((intLen \ 3) + 1) * 3
      ReDim Preserve arrInput(intLen - 1)
   End If

   'Ergebnis-Array ist im 1/3 länger als das Input-Array
   ReDim arrOutput((4 * (intLen / 3)) - 1)

   'Schleife über Input-Array in 3er-Schrittweite...
   For i = 0 To intLen - 1 Step 3
      
      '3 Byte lesen
      arrByte(1) = arrInput(i)
      arrByte(2) = arrInput(i + 1)
      arrByte(3) = arrInput(i + 2)
      
      '6 Bit extrahieren
      arrChar(1) = Int(arrByte(1) / 4)
      arrChar(2) = (arrByte(1) And 3) * 16 + Int(arrByte(2) / 16)
      arrChar(3) = (arrByte(2) And 15) * 4 + Int(arrByte(3) / 64)
      arrChar(4) = arrByte(3) And 63
      
      'Laufvariable um 1/3 erhöhen
      j = (i \ 3) * 4
      
      '6-Bit-Wert im Output-Array durch Base64-Array-Wert ersetzen
      arrOutput(j) = arrChars64(arrChar(1))
      arrOutput(j + 1) = arrChars64(arrChar(2))
      arrOutput(j + 2) = arrChars64(arrChar(3))
      arrOutput(j + 3) = arrChars64(arrChar(4))
   
   Next

   'Überzählige Bytes im Output mit Füll-Byte "=" belegen
   Select Case intDelta
      Case 1 '2 Bit
         arrOutput(UBound(arrOutput)) = 61
         arrOutput(UBound(arrOutput) - 1) = 61
      Case 2 '4 Bit
         arrOutput(UBound(arrOutput)) = 61
   End Select

   'Output-Array in String umwandeln
   EncodeBase64 = StrConv(arrOutput, vbUnicode)

End Function

Dekodieren

Das dekodieren funktioniert genau andersherum wie das Kodieren, wobei alle nicht in der base64-Zeichentabelle enthaltenen Zeichen ignoriert werden.

Public Function DecodeBase64(strInput As String) As String

   Dim arrChars64() As Byte
   Dim arrChars64Rev() As Byte
   Dim arrInput() As Byte
   Dim arrOutput() As Byte
   Dim arrChar(4) As Integer
   Dim intLen As Long
   Dim intDelta As Long
   Dim i As Long
   Dim j As Long

   Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
   
   'Zeichentabelle in Byte-Array ablegen
   arrChars64() = StrConv(Base64, vbFromUnicode)
   
   'Hilfs-Array für Umkehrtabelle dimensionieren
   ReDim arrChars64Rev(255)

   'Zeichentabelle in Hilfs-Array überkreuz übertragen
   For i = 0 To UBound(arrChars64)
      arrChars64Rev(arrChars64(i)) = i
   Next i
   
   'Länge ermitteln und prüfen
   intLen = Len(strInput)
   If intLen = 0 Then Exit Function

   'Wenn Input nicht glatt durch 4 teilbar...
   intDelta = intLen Mod 4
   If intDelta > 0 Then
      '... Input-Array mit Nullen auffüllen
      strInput = strInput + String$(4 - intDelta, 0)
      intLen = Len(strInput)
   End If

   'Input in Byte-Array umgewandeln
   arrInput() = StrConv(strInput, vbFromUnicode)
   
   'Output-Array 1/3 kleiner als das Input-Array dimensionieren
   ReDim arrOutput(((intLen + 1) / 4) * 3)

   'Schleife über Input-Array in 4er-Schrittweite...
   For i = 0 To UBound(arrInput) Step 4
   
      '4 Byte lesen
      arrChar(1) = arrChars64Rev(arrInput(i))
      arrChar(2) = arrChars64Rev(arrInput(i + 1))
      arrChar(3) = arrChars64Rev(arrInput(i + 2))
      arrChar(4) = arrChars64Rev(arrInput(i + 3))
      
      'in 8 Bit umwandeln
      arrOutput(j) = ((arrChar(1) * 4 + Int(arrChar(2) / 16)) And 255)
      j = j + 1
      arrOutput(j) = ((arrChar(2) * 16 + Int(arrChar(3) / 4)) And 255)
      j = j + 1
      arrOutput(j) = ((arrChar(3) * 64 + arrChar(4)) And 255)
      j = j + 1
      
   Next

   'Byte-Array in String umwandeln und NullChars entfernen
   DecodeBase64 = Replace(StrConv(arrOutput, vbUnicode), vbNullChar, "")

End Function

Wer das base64-Verfahren etwas näher betrachten möchte, dem sei die Seite von Arndt Brünner empfohlen, der sich neben vielen anderen mathematischen Problemen auch mit dieser Kodierung beschäftigt.
Weiterhin zu empfehlen ist eine Seite aus dem HTML-Standardwerk SelfHTML. Dort findet man auch auch eine sehr gute JavaScript-Implementierung.

Downloads

modBase64.zip
kick it on dotnet-kicks.de AddThis 0 wikio-Stimme(n) Trackback-Url...

Schlagworte

219 Kommentare bislang...

  • lycra Spandex Zentai Suits are worn by a lot of young women for pleasure and fun. These are body tight zentai suit that stick around your body to reveal the exact shape of your body. These catsuits are normally made from lycra suit that shows your figure and gives erotic pleasure to explore their wild beauty and Sexy Costumes. It is made up of latex rubber which is shiny and skin tight as if you have a skin covering your original skin, its so tight! Being shiny it gives your body an erotic and porn look, cheap zentai is a full body outfit.
    219
    Jesse : Donnerstag, 10. Mai 2012 11:17
  • Sexy lingerie and Sexy Costumes definitely adds up to the flair and experience for the most intimate and romantic evenings with your loved ones. It's a great way to surprise your partner with an exotic new look and can surely fire up the ambiance. sexy underwear and Sexy Clubwear are designed for both nightgowns for women and Men sexy Costumes. When it comes to wearing them, you don't have to time it during a special occasion, such as Sexy High Heels, High Heels Pumps and High Heels sandals. You can choose to wear them any time of the day or night as long as you feel like it.
    218
    longyuelt : Donnerstag, 10. Mai 2012 11:16
  • <a href="http://www.cheapzentai.co.uk/lycra-spandex-zentai-suits-1173_1182" title="lycra Spandex Zentai Suits">lycra Spandex Zentai Suits</a> are worn by a lot of young women for pleasure and fun. These are body tight <a href="http://www.cheapzentai.co.uk/catsuits-zentai-1173" title="zentai suit">zentai suit</a> that stick around your body to reveal the exact shape of your body. ag zentai suits</a>.
    217
    Jesse : Donnerstag, 10. Mai 2012 11:13


  • Marc Jacobs BagsThe macqbsdgpl IPO is expected to be tLongchamp Bagshe largest ever by anLongchamp Internet-based company. macpldtim ThIsabel Marant Sneakere date of the launch has reIsabel Marant Onlinemained somewhat in limbo as Facebook awaited approval fromIsabel Marant Sneaker Longchamp Bagsthe SecuriLongchamp Handbagsties anIsabel Marant Sneakerd Exchange Commission (SEC) of thIsabel Marant OnlineeLongchamp Handbags sociaIsabel Marant Onlinel networkIsabel Marant Sneakering site's S-1 filing, Longchamp Handbagsaccording to CNETIsabel Marant.

    216
    Isabel Marant Online : Donnerstag, 10. Mai 2012 07:01
  • chaussures air max 90 Et peu de blanc, qui est, le Yaozu qui la fille du patriarche de la famille actuelle Blanc Tiger, est équivalent à la seule princesse d'un royaume, au moins, n'ont jamais osé White Tiger famille avait les mains noires des terres Yaozu ci-dessus .

    En outre, la mère de la petite blanche, mais le talent jours Fox la plus forte dans la famille, les plus grandes réalisations d'un fort, a une famille tigre blanc et les jours de l'aide à la famille Fox à des mots, par le sens commun, ne serait pas obligé.

    Cependant, la réalité est cela, la route mystérieuse étoile ancienne, puis tranquillement dans laquelle le territoire du clan tigre blanc, des dizaines de haute de neuf Ha la lumière dans le vide qui un éclat plein pendant plusieurs mois, sont bient?t au courant de l'ensemble Yaozu Ceci est un message.

    Même les nouvelles se propager rapidement aux oreilles de la préhistoire parmi les forces majeures dans l'ancienne famille, et même les moines de l'homme.

    L'impulsion d'une part les forces complexes étranges, a été abruti par le tigre blanc de la famille dragon de la famille de la famille commune basaltique, dont la race Yaozu animal antique, a lancé une lutte contre l'oppression de la famille tigre blanc.

    étoile ancienne route dans lequel les livres des grandes forces ont eu des dossiers détaillés, ce qui est de la route d'un des saints Swire, Dieu roi menant dans les profondeurs mystérieuses de l'univers, comme il l'a toujours de nombreux moines de trouver dans le chemin du ciel Vieux ont Pacifique saints, Dieu, roi, et même la partie la Grande du système de canaux.

    Comme le ciel de pointe, la légende, la première génération des cieux Seigneur, Star ancienne route qui a hérité le sang réel de la chute de Yuqing Swire de la Grande-Grand, et a vécu parmi les Depo Swire ciel - Kowloon Yuxi, de sorte un seul est devenu bien connu la pénurie de l'ère antique du ciel Peak.

    étoile du mystère de l'ancienne route, même la plus vieille race ne peut être implicite, ses origines, est allé au-delà du connu à la civilisation.

    Précisément à cause de cela, au-dessus de la préhistoire tous les Road Star ancienne, mènera un champ d'une violente et extrêmement sanglante, peu importe ce que les forces voulez Road Star exclusive Vieux, avec la première occasion par exemple, et peut même créer un comparable au roi Swire Dieu, la présence de la Grande.

    Cependant, c'est aussi impossible, parce que la Road Star Vieux à la tentation de personnes que prévu, mais aussi une grande, sauf s'il est en mesure de choquer le monde de la grande puissance de leur propre renaissance, sinon, ce n'est pas toutes les forces de Road Star exclusive Vieux.
    215
    chaussures air max 90 : Montag, 7. Mai 2012 03:10

Dein Kommentar hierzu...


Kommentar-Feed für diesen Beitrag
Gravatare werden unterstützt .:. eMail-Adressen werden nicht veröffentlicht
 

RSS-Feed

Die URL des Standard-Newsfeed von zerbit.de lautet:

http://www.zerbit.de/rssfeed.aspx

Login


 

 

Statistik



kürzlich kommentiert

Artikel 11

  • Datum: 17.02.2005
    Kategorie: Visual Basic 6
    Zugriffe: 6.668
    Kommentare: 219
    Trackbacks: 0

Letzte Beiträge

Kategorien

Buttons & More

Blog-Roll

Banner Piraten-Partei