在APP的网络协议中,这些对称加密和非对称加密算法常会用在APP和服务器的交互数据中request和response(部分可能会用在数据的签名),识别这些算法是非常重要的,这里给出整理好的Java版(smali层)加密算法,C/C++(so层)也类似,主要就是识别这两行
Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv)
Java版AES算法
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/*******************************************************************************
* AES加解密算法
* http://tools.lami.la/jiami/aes
* 说明:AES数据块长度为128位,所以IV长度需要为16个字符(ECB模式不用IV),密钥根据指定密钥位数分别为16、24、32个字符,IV与密钥超过长度则截取,不足则在末尾填充'\0'补足
*******************************************************************************/
public class AES {
// AES加密 Base64输出
public static String Encrypt2Base64(String PlainText, String Key, String IV, String Mode) throws Exception {
byte[] key = Key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(Mode); // "算法/模式/补码方式"
StringBuffer ivbuffer = new StringBuffer(16);
ivbuffer.append(IV);
while (ivbuffer.length() < 16) { // IV不足则在末尾填充'\0'补足
ivbuffer.append("\0");
}
if (ivbuffer.length() > 16) { // IV超过长度则截取
ivbuffer.setLength(16);
}
IvParameterSpec iv = new IvParameterSpec(ivbuffer.toString().getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(PlainText.getBytes());
// 原始加密数据
// for (int i = 0; i < encrypted.length; i++) {
// System.out.printf("0x%02X ", encrypted[i]);
// }
return Base64.getEncoder().encodeToString(encrypted);
}
// AES解密 Base64输入
public static String DecryptFromBase64(String ciphertext, String Key, String IV, String Mode) throws Exception {
byte[] key = Key.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(Mode);
StringBuffer ivbuffer = new StringBuffer(16);
ivbuffer.append(IV);
while (ivbuffer.length() < 16) {
ivbuffer.append("\0");
}
if (ivbuffer.length() > 16) {
ivbuffer.setLength(16);
}
IvParameterSpec iv = new IvParameterSpec(ivbuffer.toString().getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] encrypted1 = Base64.getDecoder().decode(ciphertext); // 先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
// AES byte数组输入
public static String DecryptFromByte(byte[] Src, String Key, String Mode) throws Exception {
byte[] key = Key.getBytes("ASCII");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(Mode);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encrypted1 = Src;
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static void main(String[] args) throws Exception {
String Key = "DATA_KEY20150116";
// 需要加密的字串
String plaintext = "{\"data\":{\"page\":1,\"pageSize\":100},\"device\":\"android\",\"imei\":\"867514021468675\",\"mac\":\"\",\"token\":\"\",\"versionId\":\"4.2.9\"}";
System.out.println(plaintext);
// 加密
String ciphertext = AES.Encrypt2Base64(plaintext, Key, "20150116", "AES/CBC/PKCS5Padding");
System.out.println("加密后的字串是:" + ciphertext);
// 解密
String plaintext2 = AES.DecryptFromBase64(ciphertext, Key, "20150116", "AES/CBC/PKCS5Padding");
System.out.println("解密后的字串是:" + plaintext2);
// 2018全国网络空间安全技术大赛 mobile3 解密
byte[] cipher = new byte[]{(byte) 0x46, (byte) 0x00, (byte) 0x94, (byte) 0x74, (byte) 0x1F, (byte) 0xAB, (byte) 0x14, (byte) 0xF0, (byte) 0xB2, (byte) 0x59, (byte) 0xA9, (byte) 0x19, (byte) 0xC0, (byte) 0x43, (byte) 0xDC, (byte) 0xC3};
Key = "com.example.forc";
String flag = AES.DecryptFromByte(cipher, Key, "AES/ECB/NoPadding");
System.out.println("flag是:" + flag); // Xgd-aNdr1d-cTf2 不足16位补'\0'
}
}
Java版DES算法
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
public class DES {
// The initialization vector(IV) should be 8 bytes
private final static byte[] EncryptionIV = new byte[]{18, 52, 86, 120, -112, -85, -51, -17}; // 初始化向量
private final static byte[] key = new byte[]{88, 81, -114, 39, -127, -23, 64, 0};
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
String plainText = "{\"data\":{\"activityIds\":\"\",\"longitude\":116.356247,\"latitude\":23.964974},\"clientInfo\":\"23000,yingyongbao,1,44400\",\"token\":\"\",\"version\":1}";
DESKeySpec keySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(keySpec); // 密钥生成器产生真正的DES密钥
IvParameterSpec iv = new IvParameterSpec(EncryptionIV);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] cipherData = cipher.doFinal(plainText.getBytes());
System.out.println("DES加密:" + Base64.getEncoder().encodeToString(cipherData));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] plainData = cipher.doFinal(cipherData);
System.out.println("DES解密:" + new String(plainData));
byte[] ReturnData = Base64.getDecoder().decode("2Bh+ptjGW1ud/kfNtZF5NAaBEyhroftSESPJdLwDS97v355tT2X2/Rw6gM6SO46R2QHr/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uY1OXrpMTStOod6Z6eB6aboyGL+WE3msE0lpJJPi8IEBxckezBzNlpKGfZvaCdg8Fd9ScWWATnsCecAiDzoMVm5RQUJL0Q76htVSiJDMGkBu0tKKo0wV+flDR2cscl2AJHBrh9KzfvJYpxYD4vfp7FddhXh+YLwRmzg2VG41VGf0X2jKd2Dpc7fFcT8VSxdZzFRi0DvGphBKKJw=");
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] ReturnData2 = cipher.doFinal(ReturnData);
System.out.println("服务器的数据解密:" + new String(ReturnData2));
/*******************************************************************************
3DES加密:http://tools.lami.la/jiami/des3
******************************************************************************/
IvParameterSpec iv3 = new IvParameterSpec("F15A9613".getBytes()); // IV长度需要为8个字符,IV与密钥超过长度则截取,不足则在末尾填充'\0'补足
DESedeKeySpec keySpec3 = new DESedeKeySpec("750DB8A48693A8CD58654478".getBytes()); // 密钥长度为16或24个字符
SecretKeyFactory keyFactory3 = SecretKeyFactory.getInstance("desede");
SecretKey v0 = keyFactory3.generateSecret(keySpec3);
Cipher v1 = Cipher.getInstance("desede/CBC/PKCS5Padding");
v1.init(1, v0, iv3);
System.out.println("3DES加密:" + Base64.getEncoder().encodeToString(v1.doFinal("103.0".getBytes("utf-8"))));
}
}
Java版RSA算法
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.spec.RSAPublicKeySpec;
import java.net.URLEncoder;
/**
* 1、公钥加密,私钥解密用于信息加密
* 2、私钥加密,公钥解密用于数字签名
*/
public class RSA {
/**
* 测试方法
*
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
String publicKey = "MIGfMA0GCSqGS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钥解密
String enStr1 = RSA.encryptByPublic(str, publicKey);
System.out.println("公钥加密后:" + enStr1);
String deStr1 = RSA.decryptByPrivate(enStr1, privateKey);
System.out.println("私钥解密后:" + deStr1);
// 私钥加密,公钥解密
String enStr2 = RSA.encryptByPrivate(str, privateKey);
System.out.println("私钥加密后:" + enStr2);
String deStr2 = RSA.decryptByPublic(enStr2, publicKey);
System.out.println("公钥解密后:" + deStr2);
// 产生签名
String sign = sign(enStr2, privateKey);
System.out.println("签名:" + sign);
// 验证签名
boolean status = verify(enStr2, publicKey, sign);
System.out.println("状态:" + status);
}
/**
* 公钥加密
*
* @param encryptingStr
* @param publicKeyStr
* @return
*/
public static String encryptByPublic(String encryptingStr, String publicKeyStr) {
try {
// 将公钥由字符串转为UTF-8格式的字节数组
byte[] publicKeyBytes = decryptBase64(publicKeyStr);
// 获得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
// 取得待加密数据
byte[] data = encryptingStr.getBytes("UTF-8");
KeyFactory factory;
factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 返回加密后由Base64编码的加密信息
return encryptBase64(cipher.doFinal(data));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 私钥解密
*
* @param encryptedStr
* @param privateKeyStr
* @return
*/
public static String decryptByPrivate(String encryptedStr, String privateKeyStr) {
try {
// 对私钥解密
byte[] privateKeyBytes = decryptBase64(privateKeyStr);
// 获得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
// 获得待解密数据
byte[] data = decryptBase64(encryptedStr);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// 返回UTF-8编码的解密信息
return new String(cipher.doFinal(data), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 私钥加密
*
* @param encryptingStr
* @param privateKeyStr
* @return
*/
public static String encryptByPrivate(String encryptingStr, String privateKeyStr) {
try {
byte[] privateKeyBytes = decryptBase64(privateKeyStr);
// 获得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
// 取得待加密数据
byte[] data = encryptingStr.getBytes("UTF-8");
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
// 返回加密后由Base64编码的加密信息
return encryptBase64(cipher.doFinal(data));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 公钥解密
*
* @param encryptedStr
* @param publicKeyStr
* @return
*/
public static String decryptByPublic(String encryptedStr, String publicKeyStr) {
try {
// 对公钥解密
byte[] publicKeyBytes = decryptBase64(publicKeyStr);
// 取得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
// 取得待加密数据
byte[] data = decryptBase64(encryptedStr);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
// 返回UTF-8编码的解密信息
return new String(cipher.doFinal(data), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 用私钥对加密数据进行签名
*
* @param encryptedStr
* @param privateKey
* @return
*/
public static String sign(String encryptedStr, String privateKey) {
String str = "";
try {
//将私钥加密数据字符串转换为字节数组
byte[] data = encryptedStr.getBytes();
// 解密由base64编码的私钥
byte[] bytes = decryptBase64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance("RSA");
// 取私钥对象
PrivateKey key = factory.generatePrivate(pkcs);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(key);
signature.update(data);
str = encryptBase64(signature.sign());
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 校验数字签名
*
* @param encryptedStr
* @param publicKey
* @param sign
* @return 校验成功返回true,失败返回false
*/
public static boolean verify(String encryptedStr, String publicKey, String sign) {
boolean flag = false;
try {
//将私钥加密数据字符串转换为字节数组
byte[] data = encryptedStr.getBytes();
// 解密由base64编码的公钥
byte[] bytes = decryptBase64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance("RSA");
// 取公钥对象
PublicKey key = factory.generatePublic(keySpec);
// 用公钥验证数字签名
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(key);
signature.update(data);
flag = signature.verify(decryptBase64(sign));
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* BASE64 解码
*
* @param key 需要Base64解码的字符串
* @return 字节数组
*/
public static byte[] decryptBase64(String key) {
return Base64.getDecoder().decode(key);
}
/**
* BASE64 编码
*
* @param key 需要Base64编码的字节数组
* @return 字符串
*/
public static String encryptBase64(byte[] key) {
return new String(Base64.getEncoder().encode(key));
}
}