---
title: "base64编码"
author: "googya"
date: "2010-06-03T08:12:22Z"
tags: ["ASP", "HTML", "Ruby"]
categories: ["编程语言"]
slug: "base64"
draft: false
lastmod: "2010-06-22T08:51:28Z"
id: 682555
url: "https://googya.iteye.com/blog/682555"
---

受<span style="color:blue">[有道难题](http://www.iteye.com/topic/679255)</span>中许多答复者的启发，我决定对base64编码也研究一下，因为看起来这个问题在Ruby下是相当的easy。<span style="color:red">这种做法的问题在于：诸如汉字这样的字符不能还原。</span>。代码如下：

```Ruby

BASE="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def enBASE64(s)
	s.unpack("B*")[0].scan(/\d{1,6}/).map!{|x|
		if x.size==6
			BASE[("0"*2+x).to_i(2)].chr
		elsif		
	  	m=BASE[("0"*2+x.ljust(6,"0")).to_i(2)].chr + ("="*((x.size)%3))#这里主要是填充'='
	  	m
		end
	}.join
end

p enBASE64("if not this is love")

def deBASE64(s)
	i=s.count('=')
	s.tr!('=','')		
	t=s.split(//)
	t.map!{|x|
		g="%08b" %BASE.index(x)
		if i==0 || x!=t.last		
			g[2,6]
		else 		
			i==1?g[2,4]:g[2,2]	#根据填充符号（=）的数量，提取相应的长度	
  	end
  }
   t.join.scan(/\d{8}/).map{|x|x.to_i(2).chr}.join	
end
 p deBASE64("aWYgbm90IHRoaXMgaXMgbG92ZQ==")

```

是不是很简单，其实用

```Ruby

    def encode64(bin)
    [bin].pack("m")
  end


```

也可以很简单的实现,同样的，解密也很简单。但是其中隐藏了许多的细节，我们并不清楚，对于我们掌握base64编码的原理并没有帮助。自己写一个的话，可以了解其中的奥秘。


主要参考资料：
[http://en.wikipedia.org/wiki/Base64](http://en.wikipedia.org/wiki/Base64)
[矛与盾的较量（4）——奇妙的Base64编码](http://www.luocong.com/articles/show_article.asp?Article_ID=17)
[http://tools.ietf.org/html/rfc3548#section-3](http://tools.ietf.org/html/rfc3548#section-3)