1、Aes加密,密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。
package com.example.nsc.dataencryptproject;
import android.util.Log;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by 550211 on 2018/3/31.
*
* 加密的key和解密的key必须要一样
*/
public class AesUtils {
private final String TAG = "AesUtils";
private SecretKeySpec key = null;
private final String ENCRYPT_TYPE = "AES";
private SecretKeySpec getKey(String password) {
KeyGenerator keyGenerator = null;
try {
keyGenerator = KeyGenerator.getInstance(ENCRYPT_TYPE);
//256 bits or 128 bits,192bits
keyGenerator.init(128, new SecureRandom(password.getBytes()));
//AES中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
SecretKey secretKey = keyGenerator.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
if (key == null) {
key = new SecretKeySpec(enCodeFormat, ENCRYPT_TYPE);
}
} catch (NoSuchAlgorithmException e) {
Log.e(TAG,"getKey="+e.getMessage());
}
return key;
}
/**
* 数据加密
*
* @param content
* @param password
* @return
*/
public byte[] encrypt(String content, String password) {
try {
byte[] byteContent = content.getBytes("utf-8");
Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);// 创建密码器
//初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, getKey(password));// 初始化
//执行操作
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (Exception e) {
Log.e(TAG, "e=" + e.getMessage());
}
return null;
}
/**
* 解密
*
* @param content
* @param password
* @return
*/
public String decrypt(byte[] content, String password) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPT_TYPE);// 创建密码器
//初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getKey(password));
//执行操作
byte[] result = cipher.doFinal(content);
return new String(result, "UTF-8"); // 解密
} catch (Exception e) {
Log.e(TAG, "e=" + e.getMessage());
}
return null;
}
}
2、Des加密,
DES 使用一个 56 位的密钥以及附加的 8 位奇偶校验位,产生最大 64 位的分组大小。这是一个迭代的分组密码,使用称为 Feistel 的技术,其中将加密的文本块分成两半。使用子密钥对其中一半应用循环功能,然后将输出与另一半进行"异或"运算;接着交换这两半,这一过程会继续下去,但最后一个循环不交换。DES 使用 16 个循环,使用异或,置换,代换,移位操作四种基本运算。
package com.example.nsc.dataencryptproject;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import android.util.Base64;
import android.util.Log;
public class DesUtils {
private final String TAG = "DesUtils";
public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
private final static String HEX = "0123456789ABCDEF";
private static final String SHA1PRNG = "SHA1PRNG";
public String generateKey() {
try {
SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1PRNG);
//秘钥长度
byte[] bytes_key = new byte[20];
localSecureRandom.nextBytes(bytes_key);
String str_key = toHex(bytes_key);
return str_key;
} catch (Exception e) {
Log.e(TAG, "generateKey e=" + e.getMessage());
}
return null;
}
private void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
//二进制转字符
public String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
/**
* DES算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
*/
public String encode(String key, String data) {
return encode(key, data.getBytes());
}
/**
* DES算法,加密
*
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
*/
private String encode(String key, byte[] data) {
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data);
return Base64.encodeToString(bytes, 0);
} catch (Exception e) {
Log.e(TAG, "encode e=" + e.getMessage());
}
return null;
}
/**
* DES算法,解密
*
* @param data 待解密字符串
* @param key 解密私钥,长度不能够小于8位
* @return 解密后的字节数组
* @throws Exception 异常
*/
private byte[] decode(String key, byte[] data) {
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
return cipher.doFinal(data);
} catch (Exception e) {
Log.e(TAG, "decode e=" + e.getMessage());
}
return null;
}
/**
* 解密.
*
* @param key
* @param data
* @return
* @throws Exception
*/
public String decode(String key, String data) {
byte[] datas;
String value = null;
try {
if (System.getProperty("os.name") != null
&& (System.getProperty("os.name").equalsIgnoreCase("sunos") || System
.getProperty("os.name").equalsIgnoreCase("linux"))) {
datas = decode(key, Base64.decode(data, 0));
} else {
datas = decode(key, Base64.decode(data, 0));
}
value = new String(datas);
} catch (Exception e) {
value = "";
Log.e(TAG, "decode=" + e.getMessage());
}
return value;
}
}
使用代码:
package com.example.nsc.dataencryptproject;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etContent;
private Button btnAes;
private Button btnDes;
private TextView tvShow;
//加密或者解密
private boolean isEncrypt = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
etContent = (EditText) findViewById(R.id.et_content);
btnAes = (Button) findViewById(R.id.btn_aes);
btnAes.setOnClickListener(this);
btnDes = (Button) findViewById(R.id.btn_des);
btnDes.setOnClickListener(this);
tvShow = (TextView) findViewById(R.id.tv_show);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_aes:
AesUtils aes = new AesUtils();
String content = etContent.getText().toString();
if (!TextUtils.isEmpty(content)) {
if (!isEncrypt) {
byte[] encryptContent = aes.encrypt(content, "123456789");
tvShow.setText(encryptContent + "");
btnAes.setText("AES加密");
isEncrypt = true;
} else {
String aa = aes.decrypt(aes.encrypt(content, "123456789"), "123456789");
tvShow.setText(aa);
btnAes.setText("AES解密");
isEncrypt = false;
}
} else {
Toast.makeText(getApplication(), "内容不能为空", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_des:
DesUtils desUtils = new DesUtils();
String desContent = etContent.getText().toString();
String key = desUtils.generateKey();
String aa = desUtils.encode(key, desContent);
if (!isEncrypt) {
tvShow.setText(aa + "");
isEncrypt = true;
}else {
if (aa!=null){
tvShow.setText(desUtils.decode(key,aa));
}
isEncrypt = false;
}
break;
}
}
}