编码,解码(Base64,md5,sha)
1.Base64作用
编码和解码,
兼容一些老系统 比如邮件发送
//按钮事件
public void base64EncodeDemo(View view) {
String content = mEt.getText().toString();
//使用base64进行编码
String encode_content = Base64.encodeToString(content.getBytes(),Base64.DEFAULT);
mEt.setText(encode_content);
}
public void base64DecodeDemo(View view) {
String content = mEt.getText().toString();
//使用base64进行解码
byte[] decodeContent = Base64.decode(content.getBytes(),Base64.DEFAULT);
mEt.setText(new String(decodeContent));
}
2.md5
单项加密
16进制字符串的个数32
校验传输内容
public void md5MessageDigest(View view) {
try {
//获取对应算法的加密实体
MessageDigest md = MessageDigest.getInstance("MD5");
//设置要加密的文本
md.update(mEt.getText().toString().getBytes());
//生成摘要
byte[] digest = md.digest();
bytes2Hex(digest);
//10010101
//00000000 11111111
//00000000 10010101
//255
// byte & byte[2] 00000000 11111111
//00000000 10010101
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
private String bytes2Hex(byte[] data){
StringBuffer buffer = new StringBuffer();
int v = 0xa;
for (int i = 0; i < data.length; i++) {
// 10101010
//00000000 00000000 00000000 11111111
//00000000 00000000 00000000 10101010
int value = data[i] & 255;
//
//value =17 11
//value =10 a;
//10
//16进制的表现形式 0a
System.out.println("value="+value);
String temp = "";
if (value<16){
temp = "0"+Integer.toHexString(value);
}else {
temp = Integer.toHexString(value);
}
buffer.append(temp);
}
System.out.println("hexString="+buffer.toString());
System.out.println("hexStringLen="+buffer.toString().length());
return buffer.toString();
}
3.sha 高级的单项加密算法
sha-1 40位
sha-224 56位
sha-256 64位
sha-384 96位
sha-512 128位
try {
MessageDigest messageDigest =MessageDigest.getInstance("SHA-1");
messageDigest =MessageDigest.getInstance("SHA-224");
messageDigest =MessageDigest.getInstance("SHA-256");
messageDigest =MessageDigest.getInstance("SHA-384");
messageDigest =MessageDigest.getInstance("SHA-512");
messageDigest.update(mEt.getText().toString().getBytes());
byte[] result = messageDigest.digest();
String hexString = bytes2Hex(result);
((TextView)findViewById(R.id.tv_digest)).setText(hexString);