您的位置:首页 > 其它

用base64加解密解决用xml传输图片或附件生成时出现乱码的问题

2008-11-13 10:18 1151 查看
Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,在发送电子邮件时,服务器认证的用户名和密码需要用Base64编码,附件也需要用Base64编码。
下面简单介绍Base64算法的原理,由于代码太长就不在此贴出
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
转换后,我们用一个码表来得到我们想要的字符串(也就是最终的Base64编码),这个表是这样的:
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
原文的字节最后不够3个的地方用0来补足,转换时Base64编码用=号来代替。这就是为什么有些Base64编码会以一个或两个等号结束的原因,但等号最多只有两个。
举一个例子,abc经过Base64编码以后的结果是YWJj.

private static final String CHARSET_NAME = "ISO8859_1";

public static byte[] base64Decode(String s) throws IOException,

javax.mail.MessagingException {

if (s == null || s.length() == 0) {

return null;

}

ByteArrayInputStream bais = new ByteArrayInputStream(s

.getBytes(CHARSET_NAME));

InputStream is = MimeUtility.decode(bais, "base64");

ByteArrayOutputStream out = new ByteArrayOutputStream();

int ch = -1;

while ((ch = is.read()) != -1) {

out.write(ch);

}

out.flush();

bais.close();

return out.toByteArray();

}

public static String base64Encode(byte[] buf) throws IOException,

javax.mail.MessagingException {

if (buf == null || buf.length == 0) {

return "";

}

InputStream is = new ByteArrayInputStream(buf);

BufferedInputStream bis = new BufferedInputStream(is);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

OutputStream os = javax.mail.internet.MimeUtility

.encode(baos, "base64");

int chr = -1;

while ((chr = bis.read()) != -1) {

os.write(chr);

}

bis.close();

baos.close();

return new String(baos.toByteArray(), CHARSET_NAME);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐