场景:
在进行jmeter批量登录时,需要手机号码及AES加密后的手机号码
思路:
1.将手机号码存入csv文件;
2.读取csv文件中的手机号到list集合中;
3.遍历集合将数据分组存入map集合;
4.遍历map集合,调用AES加密类,将手机号进行AES加密处理,并将结果写入csv文件。
代码:
MobileInfo.java
package file_test;
public class MobileInfo {
private String phone;
private String aes_phone;
public String getAes_phone() {
return aes_phone;
}
public void setAes_phone(String aes_phone) {
this.aes_phone = aes_phone;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
csvRead.java
package file_test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import aes_test2.AesUtil;
public class csvRead {
public static void main(String[] args){
List<MobileInfo> mobileinfos = new ArrayList<MobileInfo>();//保存读取csv得到的数据
Map<String, List<MobileInfo>> map = new HashMap<String, List<MobileInfo>>();//phone,aes_phone的map集合
String phone = null;
List<MobileInfo> mapMobileInfos = new ArrayList<MobileInfo>();//map集合中phone的对应的对象集合
BufferedReader reader = null;
//读写csv数据到list(mobileinfos)集合中
try {
reader = new BufferedReader(new FileReader("D://phone.csv"));//换成你的文件名
String line = null;
while((line=reader.readLine())!=null){
String data[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
MobileInfo dkinfo = new MobileInfo();
dkinfo.setPhone(data[0]);
//dkinfo.setAes_phone(data[1]);
mobileinfos.add(dkinfo);
System.out.println(data[0]);
}
//遍历集合,将数据分组存入map集合
for(MobileInfo mobileinfo : mobileinfos){
phone = mobileinfo.getPhone();
mapMobileInfos = map.get(phone);//获取对应phone的集合,第一次获取时为空
if(mapMobileInfos == null){//这里如果不进行为空判断,会报空指针异常
mapMobileInfos = new ArrayList<MobileInfo>();
}
mapMobileInfos.add(mobileinfo);//将新添加的对象加入到对应的phone的对象集合
map.put(phone, mapMobileInfos); //将每次新添加对象后的对象集合存入对应map中
}
//遍历map集合,并将结果写入新的csv文件
File newcsv=new File("D://newcsv.csv");
BufferedWriter bw=new BufferedWriter (new FileWriter(newcsv,true));
for (Map.Entry<String, List<MobileInfo>> entry : map.entrySet()) {
String bright_phone=entry.getKey();
AesUtil aes = new AesUtil();
String encStr = aes.encryptByHex(bright_phone);//使用aes加密手机号
//将加密后的数据写入csv
bw.write(entry.getKey() + "," + encStr);
System.out.println("手机号 = " + entry.getKey() + ", AES加密手机号 = " + encStr);
bw.newLine();//换行
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
reader.close();
mobileinfos.clear();
map.clear();
mapMobileInfos.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
处理后的csv文件
附赠AESUtil.java
package aes_test2;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.File;
import jxl.*;
/**
* @ProjectName: xcloud
* @Package: com.bo.xcloud.common.crypto.bcrypt
* @ClassName: AesUtil
* @Author: it-bo
* @Date: 2019/6/5 15:01
* @Description: AES加密工具类
* @Version: 1.0
*/
@Component
public class AesUtil {
/**
* @author ngh
* AES128 算法
* <p>
* CBC 模式
* <p>
* PKCS7Padding 填充模式
* <p>
* CBC模式需要添加一个参数iv
* <p>
* 介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别
* 要实现在java端用PKCS7Padding填充,需要用到bouncycastle组件来实现
*/
private Key key;
private Cipher cipher;
boolean isInited = false;
byte[] iv = "0103021405060878".getBytes(); //偏移量
//byte[] keyBytes = "cccccccc".getBytes(); //秘钥1
byte[] keyBytes = "bbbbbbbb".getBytes(); //秘钥2
byte[] scrtBytes="aaaaaaaa".getBytes(); //秘钥3
public void init(byte[] keyBytes) {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyBytes.length % base != 0) {
int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
keyBytes = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
// 转化成JAVA的密钥格式
key = new SecretKeySpec(keyBytes, "AES");
try {
// 初始化cipher
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String encrypt(String content) {
return Base64.encode(encrypt(content.getBytes(), keyBytes));
}
public String encrypt(String content, String keyBytes) {
return Base64.encode(encrypt(content.getBytes(), keyBytes.getBytes()));
}
public String encryptByHex(String content) {
return HexUtil.encodeHexStr(encrypt(content.getBytes(), keyBytes));
}
public String encryptByHex(String content, String keyBytes) {
return HexUtil.encodeHexStr(encrypt(content.getBytes(), keyBytes.getBytes()));
}
/**
* 加密方法
*
* @param content 要加密的字符串
* @param keyBytes 加密密钥
* @return
*/
public byte[] encrypt(byte[] content, byte[] keyBytes) {
byte[] encryptedText = null;
keyBytes = new String(keyBytes).getBytes();
init(keyBytes);
try {
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
encryptedText = cipher.doFinal(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedText;
}
public String decrypt(String encryptedData) {
return new String(decrypt(Base64.decode(encryptedData), keyBytes));
}
public String decrypt(String encryptedData, String keyData) {
return new String(decrypt(Base64.decode(encryptedData), keyData.getBytes()));
}
public String decryptByHex(String encryptedData) {
return new String(decrypt(HexUtil.decodeHex(encryptedData), keyBytes));
}
public String decryptByHex(String encryptedData, String keyData) {
return new String(decrypt(HexUtil.decodeHex(encryptedData), keyData.getBytes()));
}
/**
* 解密方法
*
* @param encryptedData 要解密的字符串
* @param keyBytes 解密密钥
* @return
*/
public byte[] decrypt(byte[] encryptedData, byte[] keyBytes) {
byte[] encryptedText = null;
init(keyBytes);
try {
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
encryptedText = cipher.doFinal(encryptedData);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedText;
}
/**
* 苏康码AES加密
*
* @param sSrc
* @param
* @return
* @throws Exception
*/
public static String encryptSu(String sSrc, String key) {
String sKey = secureBytes(key);
try {
if (sSrc == null || sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byte2hex(encrypted).toLowerCase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 密钥如超过16位,截至16位,不足16位,补/000至16位
*
* @param
* @return 新密钥
*/
public static String secureBytes(String key) {
if (key.length() > 16) {
key = key.substring(0, 16);
} else if (key.length() < 16) {
for (int i = (key.length() - 1); i < 15; i++) {
key += "\000";
}
}
return key;
}
/**
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 苏康码AES解密
*
* @param sSrc
* @param
* @return
* @throws Exception
*/
public static String decryptSu(String sSrc, String key) {
String sKey = secureBytes(key);
try {
// 判断Key是否正确
if (sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.println("长度不是16");
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
// String originalString = new String(original, "GBK");
return originalString;
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
}
/**
* @param strhex
* @return
*/
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
public static void main(String[] args) {
//测试
AesUtil aes = new AesUtil();
//加密字符串
System.out.println("手机号aes加密");
String card_code = "15333333333";
// 加密方法
String encStr = aes.encryptByHex(card_code, "xxxxxxx");
System.out.println("加密后的内容:" + encStr);
String decStr = aes.decryptByHex(encStr, "xxxxxx");
System.out.println("解密后的内容:" + decStr);
}
}