s c h e m a t i c s : c o o k b o o k

/ Cookbook.WebBase64Encoding

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Encoding Data Using Base 64

Problem

You want to encode a string using the Base64 encoding, for instance to send a username and password using HTTP Basic Authentication

Solution

The following routine encodes a string into it's Base64 equivalent using the default string to byte conversion. Note that lines are not broken at 76 characters. This is the correct rule for most web applications.

(require (lib "base64.ss" "net"))

;; base64-encode : string -> string
(define (base64-encode string)
  (let ((output (open-output-string)))
    (base64-encode-stream
     (open-input-string string)
     output
     #"")
    (get-output-string output)))

An example usage:

> (base64-encode "Scheme Rules")
"C2nozw1lihj1bgvz"

Discussion

The net collection provides routines to perform Base64 encoding. They are oriented towards encoding attachments for inclusion in email. In this situation line length is limited to 76 characters. Most other applications, for example HTTP Basic Authentication, don't have this limitation.

Base64 is only defined for 8-bit values, so some conversion must be used to turn string characters to bytes. The implementation above uses the UTF-8 encoding, which is the default for string ports.


Comments about this recipe

Contributors

-- NoelWelsh - 17 Dec 2005

CookbookForm
TopicType: Recipe
ParentTopic: WebRecipes
TopicOrder: 999

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest