Java implementation of BASE64 encoding

Source: Internet
Author: User
Tags base64



Java itself is a toolkit that provides BASE64 encoding, and when the project is done by itself, it is recorded here:


1 / ** Base64 encoded array * /
 2 private static final String base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
 3
 4 / **
 5 * Base64 encoding
 6 * @param str string to be encoded
 7 * @return
 8      */
 9 public static String base64encode (String str) {
10 String out = "";
11 int i = 0;
12 int len = str.length ();
13 int c1, c2, c3;
14 while (i <len) {
15 c1 = str.charAt (i ++) & 0xff;
16 if (i == len) {
17 out + = base64EncodeChars.charAt (c1 >> 2);
18 out + = base64EncodeChars.charAt ((c1 & 0x3) << 4);
19 out + = "==";
20 break;
twenty one             }
22 c2 = str.charAt (i ++);
23 if (i == len) {
24 out + = base64EncodeChars.charAt (c1 >> 2);
25 out + = base64EncodeChars.charAt (((c1 & 0x3) << 4)
26 | ((c2 & 0xF0) >> 4));
27 out + = base64EncodeChars.charAt ((c2 & 0xF) << 2);
28 out + = "=";
29 break;
30}
31 c3 = str.charAt (i ++);
32 out + = base64EncodeChars.charAt (c1 >> 2);
33 out + = base64EncodeChars.charAt (((c1 & 0x3) << 4)
34 | ((c2 & 0xF0) >> 4));
35 out + = base64EncodeChars.charAt (((c2 & 0xF) << 2)
36 | ((c3 & 0xC0) >> 6));
37 out + = base64EncodeChars.charAt (c3 & 0x3F);
38}
39 return out;
40} 


If you want to generate a URL-safe Base64 encoding, you need to replace the "+" inside with "-" and replace "/" with "_"


1     /**
2 * Convert Base64 encoding to URL-safe Base64 encoding
3 * @param str Base64 encoded string
4 * @return
5 * /
6 private static String safe64 (String str) {
7 String result = str.replace ("+", "-");
8 return result.replace ("/", "_");
9     } 








/** BASE64 Encoded Array */
private static final String Base64encodechars = "Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789-_";



Java implementation of BASE64 encoding


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.