一、步骤
1、新建工具类,添加转换方法
package .......import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;/*** base64(sha256("aa"))算法加密*/
public class Sha256AndBase64Utils {public static String GenerateSecretKey(String inputString) {// 第一步:计算SHA-256哈希值MessageDigest messageDigest = null;try {messageDigest = MessageDigest.getInstance("SHA-256");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}byte[] inputBytes = inputString.getBytes(StandardCharsets.UTF_8);byte[] sha256HashBytes = messageDigest.digest(inputBytes);//2、将sha256byte数组转为字符串String sha256Info = byteArrayToHexString(sha256HashBytes);//3、将字符串进行base64加密return encodeToBase64(sha256Info);}//字节数组转为字符串public static String byteArrayToHexString(byte[] bytes) {return String.format("%064x", new BigInteger(1, bytes));}//对字符串进行Base64加密public static String encodeToBase64(String plainText) {// 将字符串转换为字节数组byte[] textBytes = plainText.getBytes(Charset.forName("UTF-8"));// 对字节数组进行Base64编码byte[] encodedBytes = Base64.getEncoder().encode(textBytes);// 将编码后的字节数组转换为字符串return new String(encodedBytes);}
}
2、调用方法进行加密
String T_data = "原始字符串";
String secretResult = Base64Utils.GenerateSecretKey(T_data);
Log.e("log","加密后字符串是:"+ secretResult);
3、完成,Nice!