Base 64编码和解码示例代码

有谁知道如何使用Base64解码和编码Base64中的string。 我正在使用下面的代码,但它不工作。

String source = "password"; byte[] byteArray = source.getBytes("UTF-16"); Base64 bs = new Base64(); //bs.encodeBytes(byteArray); System.out.println( bs.encodeBytes(byteArray)); //bs.decode(bs.encodeBytes(byteArray)); System.out.println(bs.decode(bs.encodeBytes(byteArray))); 

第一:

  • select一种编码。 UTF-8通常是一个不错的select; 坚持编码,这将肯定是有效的双方。 使用除UTF-8或UTF-16之外的其他内容很less见。

发送端:

  • 将string编码为字节(例如, text.getBytes(encodingName)
  • 使用Base64类将字节编码为base64
  • 传输base64

收到结束:

  • 接收base64
  • 使用Base64类将base64解码为字节
  • 将字节解码为一个string(例如new String(bytes, encodingName)

所以像这样:

 // Sending side byte[] data = text.getBytes("UTF-8"); String base64 = Base64.encodeToString(data, Base64.DEFAULT); // Receiving side byte[] data = Base64.decode(base64, Base64.DEFAULT); String text = new String(data, "UTF-8"); 

或与StandardCharsets

 // Sending side byte[] data = text.getBytes(StandardCharsets.UTF_8); String base64 = Base64.encodeToString(data, Base64.DEFAULT); // Receiving side byte[] data = Base64.decode(base64, Base64.DEFAULT); String text = new String(data, StandardCharsets.UTF_8); 

对于在search关于如何解码用Base64.encodeBytes()编码的string的信息时结束的人,这里是我的解决scheme:

 // encode String ps = "techPass"; String tmp = Base64.encodeBytes(ps.getBytes()); // decode String ps2 = "dGVjaFBhC3M="; byte[] tmp2 = Base64.decode(ps2); String val2 = new String(tmp2, "UTF-8"); 

此外,我支持Android的旧版本,所以我使用来自http://iharder.net/base64的; Robert Harder的Base64库

就像是

 String source = "password"; byte[] byteArray; try { byteArray = source.getBytes("UTF-16"); System.out.println(new String(Base64.decode(Base64.encode(byteArray, Base64.DEFAULT), Base64.DEFAULT))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

要encryption:

 byte[] encrpt= text.getBytes("UTF-8"); String base64 = Base64.encodeToString(data, Base64.DEFAULT); 

解密:

 byte[] decrypt= Base64.decode(base64, Base64.DEFAULT); String text = new String(data, "UTF-8"); 

基于以前的答案,我使用下面的实用方法,以防有人想使用它。

  /** * @param message the message to be encoded * * @return the enooded from of the message */ public static String toBase64(String message) { byte[] data; try { data = message.getBytes("UTF-8"); String base64Sms = Base64.encodeToString(data, Base64.DEFAULT); return base64Sms; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } /** * @param message the encoded message * * @return the decoded message */ public static String fromBase64(String message) { byte[] data = Base64.decode(message, Base64.DEFAULT); try { return new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }