python的base64转换:
import base64
def strToBase64(s):
'''
将字符串转换为base64字符串
:param s:
:return:
'''
strEncode = base64.b64encode(s.encode('utf8'))
return str(strEncode, encoding='utf8')
def base64ToStr(s):
'''
将base64字符串转换为字符串
:param s:
:return:
'''
strDecode = base64.b64decode(bytes(s, encoding="utf8"))
return str(strDecode, encoding='utf8')
if __name__ == '__main__':
s = "python:字符串转换成字节的三种方式"
print(strToBase64(s))
s2 = 'cHl0aG9uOuWtl+espuS4sui9rOaNouaIkOWtl+iKgueahOS4ieenjeaWueW8jw=='
print(base64ToStr(s2))
java的base64的转换:(java8)
package com.sample.test;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class Test {
/**
* 将字符串转换为base64字符串
* @param str
* @return
*/
public static String strToBase64(String str) {
byte[] bytes;
try {
bytes = Base64.getEncoder().encode(str.getBytes("utf-8"));
return new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* 将base64字符串转换为字符串
* @param str
* @return
*/
public static String base64ToStr(String str) {
try {
return new String(Base64.getDecoder().decode(str), "utf-8");
} catch (UnsupportedEncodingException e) {
return str;
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "cHl0aG9uOuWtl+espuS4sui9rOaNouaIkOWtl+iKgueahOS4ieenjeaWueW8jw==";
String r = base64ToStr(s);
System.out.println(r);
System.out.println(strToBase64(r));
}
}