常見編碼加密解密的基礎(chǔ)用法
- Base64編碼
- URL編碼
- GZIP
- AES加密
- DES加密
- RSA加密
public class MainActivity extends AppCompatActivity {
private EditText mTextContent;
private TextView mTxtResult;
private TextView mTxtPass;
private byte [] mDecode;
private byte [] mPriDecode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextContent = (EditText) findViewById (R.id.txt_content);
mTxtResult = (TextView) findViewById (R.id.txt_result);
mTxtPass = (TextView) findViewById (R.id.txt_password);
}
編碼
public void btnBase64Encode(View view) {
String str = mTextContent.getText().toString().trim();
// Base64編碼 no_wrap 代表編碼的結(jié)果沒有任何換行
String encoded = Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
mTxtResult.setText(encoded);
//Base64 解碼,
byte[] decode = Base64.decode(encoded, Base64.NO_WRAP);
String ss = new String(decode);
Log.d("Base64 ", "ss = " + ss);
}
public void btnURLEncode(View view) {
String str = "%E5%8F%98%E5%BD%A2%E9%87%91%E5%88%9A";
try {
String decode = URLDecoder.decode(str, "utf-8");
Log.d("UE", "URLENCODING: " + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//URLEncoder
try {
String encode = URLEncoder.encode("BY帥", "utf-8");
Log.d("UE", "URLENCODING: edncode: " + encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* GZIP壓縮楞抡,解壓縮
*
* @param view
*/
public void btnGzipTest(View view) {
String str = mTextContent.getText().toString().trim();
// 1.壓縮GZIP,GZIPOutPutStream
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
GZIPOutputStream gzipout = new GZIPOutputStream(bout);
gzipout.write(str.getBytes());//利用GZIPOutPutStream壓縮伟众,并輸出結(jié)果
gzipout.finish();//必須調(diào)用生成實際的壓縮數(shù)據(jù)
gzipout.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = bout.toByteArray();
mTxtResult.setText("內(nèi)容長度:" + str.length() + "\n壓縮大小:" + bytes.length);
String s = Arrays.toString(bytes);
Log.d("GZIP", s);
//解壓縮 GZIPInputStream
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
try {
GZIPInputStream gzipIn = new GZIPInputStream(bin);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int len;
while (true) {
len = gzipIn.read(buf);
if (len == -1) {
break;
}
bo.write(buf, 0, len);
}
byte[] bytes1 = bo.toByteArray();
String s1 = new String(bytes1);
Log.d("GZIP", s1);
} catch (IOException e) {
e.printStackTrace();
}
}
public void btnDesTest(View view) {
//DES TEST
String str = mTextContent.getText().toString().trim();
String pwd = mTxtPass.getText().toString().trim();
// byte[] encrypt = CryptUtil.desEncrypt(str.getBytes(), pwd.getBytes());
byte[] iv = {23, 12, 3, 2, 4, 5, 7, 3, 4, 3, 34, 66, 6, 7, 93, 12};
byte[] encrypt = CryptUtil.aesEncryptWithIv(str.getBytes(), pwd.getBytes(), iv);
String s = Base64.encodeToString(encrypt, Base64.NO_WRAP);
mTxtResult.setText(s);
//解密召廷,把Base64還原凳厢,并且解密
byte[] ed = Base64.decode(s, Base64.NO_WRAP);
byte[] data = CryptUtil.aesDecryptWithIv(ed, pwd.getBytes(), iv);
String ss = new String(data);
Log.d("DES", "btnDesTest : " + ss);
}
public void btnRsaTest(View view) {
String state = Environment.getExternalStorageState();
File dir = getFilesDir();
if (state.equals(Environment.MEDIA_MOUNTED)) {
dir = Environment.getExternalStorageDirectory();
}
if (!dir.exists()) {
dir.mkdirs();
}
Log.d("KEY", "dir : " + dir.getAbsolutePath());
File target = new File(dir, "secret.txt");
try {
if (!target.exists()) {
// 1.加載或者生成密鑰對
KeyPair keyPair = CryptUtil.generateRsaKey(1024);
// 私鑰
PrivateKey aPrivate = keyPair.getPrivate();
// 公鑰
PublicKey aPublic = keyPair.getPublic();
// 私鑰的數(shù)據(jù)格式
byte[] privEncoded = aPrivate.getEncoded();
byte[] pubEncoded = aPublic.getEncoded();
// String publicstr = aPublic.toString();
String pubkeyEncode = Base64.encodeToString(pubEncoded, Base64.NO_WRAP);
String priKeyEncode = Base64.encodeToString(privEncoded, Base64.NO_WRAP);
// Log.d("Key", publicstr);
//TODO:把公鑰,私鑰使用BASE64編碼竞慢,保存到文件中先紫,下一次啟動時,需要先加載筹煮,沒有才創(chuàng)建
target.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(target, true));
bw.write(pubkeyEncode);
bw.newLine();
bw.write(priKeyEncode);
bw.close();
BufferedReader bufferedReader = new BufferedReader(new FileReader(target));
String Pub = bufferedReader.readLine();
mDecode = Base64.decode(Pub, Base64.NO_WRAP);
String Pri = bufferedReader.readLine();
mPriDecode = Base64.decode(Pri, Base64.NO_WRAP);
bufferedReader.close();
// FileOutputStream fos = new FileOutputStream(target);
// fos.write(pubencode);
// fos.close();
}else if (target.exists()){
BufferedReader bufferedReader = new BufferedReader(new FileReader(target));
String Pub = bufferedReader.readLine();
mDecode = Base64.decode(Pub, Base64.NO_WRAP);
String Pri = bufferedReader.readLine();
mPriDecode = Base64.decode(Pri, Base64.NO_WRAP);
Log.d("key","public: " + Pub);
Log.d("key","private: " + Pri);
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(mDecode);
PKCS8EncodedKeySpec pkeySpec = new PKCS8EncodedKeySpec(mPriDecode);
RSAPrivateKey privateKey = null;
RSAPublicKey rsap = null;
KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance("RSA");
rsap = (RSAPublicKey) keyFactory.generatePublic(keySpec);
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkeySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
String str = mTextContent.getText().toString().trim();
byte[] encrypt = CryptUtil.rsaEncrypt(str.getBytes(), rsap);
String es = Base64.encodeToString(encrypt, Base64.NO_WRAP);
mTxtResult.setText(es);
byte[] dd = Base64.decode(es, Base64.NO_WRAP);
byte[] data = CryptUtil.rsaDecrypt(dd, privateKey);
String s1 = new String(data);
Log.d("RSA", "RSACry : " + s1);
}
}
加密工具類
public class CryptUtil {
private CryptUtil() {
}
/**
* DES 加密算法
*
* @param data 原始數(shù)據(jù)
* @param key 密碼遮精,必須是8個字節(jié)
* @return byte[] 經(jīng)過加密之后的內(nèi)容
*/
public static byte[] desEncrypt(byte[] data, byte[] key) {
byte[] ret = null;
if (data != null && key != null) {
if (data.length > 0 && key.length == 8) {
// 1.使用 Cipher引擎,來初始化加密败潦,并且設(shè)置密碼
try {
Cipher cipher = Cipher.getInstance("DES");
// 1.1 DESKEYSPEC用于描述 的事的密碼
DESKeySpec spec = new DESKeySpec(key);
// 1.2使用SecretKeyFactory生成Key對象
SecretKeyFactory des = SecretKeyFactory.getInstance("DES");
SecretKey sk = des.generateSecret(spec);
// 1.3初始化Cipper 為加密I操作本冲,并且制定密鑰
cipher.init(Cipher.ENCRYPT_MODE, sk);
// 2.加密數(shù)據(jù)
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
/**
* DES 解密算法
*
* @param data 原始數(shù)據(jù)
* @param key 密碼,必須是8個字節(jié)
* @return byte[] 經(jīng)過解密之后的內(nèi)容
*/
public static byte[] desDecrypt(byte[] data, byte[] key) {
byte[] ret = null;
if (data != null && key != null) {
if (data.length > 0 && key.length == 8) {
// 1.使用 Cipher引擎劫扒,來初始化解密檬洞,并且設(shè)置密碼
try {
Cipher cipher = Cipher.getInstance("DES");
// 1.1 DESKEYSPEC用于描述 的事的密碼
DESKeySpec spec = new DESKeySpec(key);
// 1.2使用SecretKeyFactory生成Key對象
SecretKeyFactory des = SecretKeyFactory.getInstance("DES");
SecretKey sk = des.generateSecret(spec);
// 1.3初始化Cipper 為解密操作,并且制定密鑰
cipher.init(Cipher.DECRYPT_MODE, sk);
// 2.解密數(shù)據(jù)
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
///////////////////////////////////////////////////////////////////////////
// AES方式
///////////////////////////////////////////////////////////////////////////
public static byte[] aesEncrySimple(byte[] data, byte[] key) {
byte[] ret = null;
if (data != null && key != null) {
if (data.length > 0 && key.length == 16) {
// AES 128bit = 16nytes
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
public static byte[] aesDecrySimple(byte[] data, byte[] key) {
byte[] ret = null;
if (data != null && key != null) {
if (data.length > 0 && key.length == 16) {
// AES 128bit = 16nytes
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
///////////////////////////////////////////////////////////////////////////
// AES 方式2 使用兩套密碼
///////////////////////////////////////////////////////////////////////////
/**
* 使用兩套密碼的加密沟饥,強(qiáng)度更高
*
* @param data 數(shù)據(jù)
* @param key 第一個密碼
* @param ivData 第二個密碼
* @return
*/
public static byte[] aesEncryptWithIv(byte[] data, byte[] key, byte[] ivData) {
byte[] ret = null;
if (data != null && key != null && ivData != null) {
if (data.length > 0 && key.length == 16 && ivData.length == 16) {
//使用兩套密碼的添怔,算法需要寫成AES/算法模式/填充模式
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//準(zhǔn)備第一套
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
//準(zhǔn)備第二套密碼
IvParameterSpec iv = new IvParameterSpec(ivData);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// ret = cipher.doFinal(data);
cipher.update(data);
ret = cipher.doFinal();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
public static byte[] aesDecryptWithIv(byte[] data, byte[] key, byte[] ivData) {
byte[] ret = null;
if (data != null && key != null && ivData != null) {
if (data.length > 0 && key.length == 16 && ivData.length == 16) {
//使用兩套密碼的,算法需要寫成AES/算法模式/填充模式
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//準(zhǔn)備第一套
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
//準(zhǔn)備第二套密碼
IvParameterSpec iv = new IvParameterSpec(ivData);
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// ret = cipher.doFinal(data);
cipher.update(data);
ret = cipher.doFinal();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
}
return ret;
}
///////////////////////////////////////////////////////////////////////////
// RSA
///////////////////////////////////////////////////////////////////////////
// 1.生成密鑰對贤旷, 公鑰和私鑰
/**
* bits 位數(shù)必須在 1024 和 2048 之間
*
* @param bits
* @return
*/
public static KeyPair generateRsaKey(int bits) {
KeyPair ret = null;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(bits);
ret = kpg.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return ret;
}
/**
* RSA 加密澎灸,使用公鑰加密,那么必須使用私鑰解密
* 使用私鑰加密遮晚,必須使用公鑰解密
*
* @param data
* @param key
* @return
*/
public static byte[] rsaEncrypt(byte[] data, Key key) {
byte[] ret = null;
if (data != null && data.length > 0 && key != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
return ret;
}
//解密
public static byte[] rsaDecrypt(byte[] data, Key key) {
byte[] ret = null;
if (data != null && data.length > 0 && key != null) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
ret = cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
return ret;
}
}