对xml 以及json格式操作
功能以下
1、将xml 以及json中的节点key 都遍历出来存储在map中,如果有重复key,则以key_2、key_3...等形式存放map中。
2、对xml以及json中的值更新,如果存在重复,则先将对应的存入list容器中,然后对容器中重复的位置来进行更新。
代码如下:
package com.suning.ibis.supplier.entity.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
/**
* 对xml 或者 json的转换使用
* @author 88397658
*
*/
public final class ConvertUtils {
public static Document getDocument(String xml) throws DocumentException{
return DocumentHelper.parseText(xml);
}
public static Element rootElement(String xml) throws DocumentException{
Document parseText = getDocument(xml);
return parseText.getRootElement();
}
/**
* 默认 索引0
* @param element
* @param elemStr
* @param value
* @throws Exception
*/
public static void changeValFromXml(Element element ,String elemStr,String value)throws Exception{
changeValFromXml(element,elemStr,value,0);
}
/**
*
* 根据key来更改xml的节点值
* @param jsonObject
* @param key
* @param updateData
* @param index 主要是针对json下可能存在相同的节点名称,index是出现的位置索引, 从0,1,2,3.。。。。
* (如不存在多个,index默认为0)
* @throws Exception
*/
public static void changeValFromXml(Element element ,String elemStr,String value,int index)throws Exception{
List<Element> elements = new ArrayList<Element>();
doChangeValFromXml(element,elemStr,elements);
index = index < 0?0:index>=elements.size()?elements.size()-1:index;
Element element2 = elements.get(index);
element2.setText(value);
}
/**
* 根据xml节点 设置值
*/
@SuppressWarnings("rawtypes")
private static void doChangeValFromXml(Element element ,String elemStr,List<Element> elements2){
List elements = element.elements();
// 没有子元素
if (elements.isEmpty())
{}
else
{
// 有子元素
Iterator it = elements.iterator();
Element elem = null;
while (it.hasNext())
{
elem = (Element)it.next();
if(elem.getName().equals(elemStr)){
elements2.add(elem);
// elem.setText(value);
// return;
}
// 递归遍历
doChangeValFromXml(elem,elemStr,elements2);
}
}
}
/**
* 将xml节点转为map
*/
@SuppressWarnings("rawtypes")
public static void convertXmlElemToMap(Element element, Map<String, String> map) {
List elements = element.elements();
// 没有子元素
if (elements.isEmpty())
{}
else
{
// 有子元素
Iterator it = elements.iterator();
Element elem = null;
while (it.hasNext())
{
elem = (Element)it.next();
String name = elem.getName();
String data = elem.getText().trim();
if(StringUtils.isNotBlank(data)){
boolean containsKey = map.containsKey(name);
if(containsKey){
int i =2;
while(true){
if(map.containsKey(name+"_"+i)){
i++;
}else{
map.put(name+"_"+i, data);
break;
}
}
}else{
map.put(name, data);
}
}
// 递归遍历
convertXmlElemToMap(elem,map);
}
}
}
/**
* 将json中所有key-value 存放入map中
* @param jsonObject
* @param map
*/
public static void convertJsonToMap(JSONObject jsonObject,Map<String, String> map){
Set<Entry<String, Object>> entrySet = jsonObject.entrySet();
for(Entry<String, Object> entry : entrySet){
JSONObject object = null;
Object value = entry.getValue();
if(value instanceof String){
String name = entry.getKey();
String data = (String) value;
if(StringUtils.isNotBlank(data)){
boolean containsKey = map.containsKey(name);
if(containsKey){
int i =2;
while(true){
if(map.containsKey(name+"_"+i)){
i++;
}else{
map.put(name+"_"+i, data);
break;
}
}
}else{
map.put(name, data);
}
}
}else if(value instanceof JSONObject){
object = (JSONObject) entry.getValue();
convertJsonToMap(object, map);
}else if(value instanceof JSONArray){
JSONArray array = (JSONArray) value;
for(Object obj:array){
JSONObject object2 = (JSONObject) obj;
convertJsonToMap(object2, map);
}
}
}
}
public static void chanageValFromJson(final JSONObject jsonObject,String key,String updateData)throws Exception{
chanageValFromJson(jsonObject, key, updateData,0);
}
/**
*
* 根据key来更改json的value
* @param jsonObject
* @param key
* @param updateData
* @param index 主要是针对json下可能存在相同的节点名称,index是出现的位置索引, 从0,1,2,3.。。。。
* (如不存在多个,index默认为0)
* @throws Exception
*/
public static void chanageValFromJson(final JSONObject jsonObject,String key,String updateData,int index)throws Exception{
List<Object> list = new ArrayList<>();
doChanageDataFromJson(jsonObject,key,list);
index = index < 0?0:index>=list.size()?list.size()-1:index;
JSONObject object2 = (JSONObject) list.get(index);
object2.put(key, updateData);
}
private static void doChanageDataFromJson(JSONObject jsonObject,String key,List<Object> list){
Set<Entry<String, Object>> entrySet = jsonObject.entrySet();
for(Entry<String, Object> entry : entrySet){
JSONObject object = null;
Object value = entry.getValue();
if(value instanceof JSONObject){
object = (JSONObject) entry.getValue();
if(object.containsKey(key)){
// object.put(key, updateData);
list.add(object);
}
doChanageDataFromJson(object, key,list);
}else if(value instanceof JSONArray){
JSONArray array = (JSONArray) value;
/*JSONObject object2 = (JSONObject) array.get(index-1);
if(object2.containsKey(key)){
object2.put(key, updateData);
return;
}
chanageDataFromJson(object2, key,updateData,index);*/
for(Object obj:array){
JSONObject object2 = (JSONObject) obj;
if(object2.containsKey(key)){
list.add(object2);
}
doChanageDataFromJson(object2, key,list);
}
}
}
}
public static void main(String[] args) throws Exception {
/*long a = System.currentTimeMillis();
String ss ="{\"sign\":{'ccc':'123',\"signValPosition\": \"1\",\"array\":[{\"name\":\"22\"},{'name':'33'}]},'addds':{\"gg\":{\"bb\":\"ccc\"}}" +
",'sign1':{'ccc':'32133',\"signValPosition1\": \"24234\",\"array\":[{\"name\":\"56546\"},{'name':'876876'}]},'addds':{\"gg\":{\"bb\":\"ccc\"}}}";
JSONObject object = JSONObject.parseObject(ss);
// System.out.println(object);
ConvertUtils.chanageValFromJson(object, "name", "崔春驰",-1);
Map<String, String> map = new HashMap<String, String>();
ConvertUtils.convertJsonToMap(object, map);
System.out.println(map.toString());
System.out.println(object);
long b = System.currentTimeMillis();
System.out.println(b-a);*/
StringBuilder sb = new StringBuilder();
try {
// 读取字符文件
BufferedReader in = new BufferedReader(new FileReader(new File("C:\\Users\\MTW\\Desktop\\4545.txt")));
// 为什么单独在这里加上try块而不是直接使用外边的try块?
// 需要考虑这么一种情况,如果文件没有成功打开,则finally关闭文件会出问题
try {
String s;
while ((s = in.readLine()) != null) {
sb.append(s + "\n");
}
}finally{
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
long a = System.currentTimeMillis();
String resXml = sb.toString();
Map<String, String> map1 = new ConcurrentHashMap<String, String>();
Element rootElement = ConvertUtils.getDocument(resXml).getRootElement();
ConvertUtils.changeValFromXml(rootElement, "ProductName", "##############",1);
ConvertUtils.convertXmlElemToMap(rootElement, map1);
System.out.println(map1.toString());
System.out.println(ConvertUtils.getXml(rootElement));
long b = System.currentTimeMillis();
System.out.println(b-a);
}
/**
* 返回xml字符串
* @param element
* @return
*/
public static String getXml(Element element){
return element.asXML();
}
}
对 加解密的操作帮助类
package com.suning.ibis.supplier.entity.common;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.util.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.suning.ios.common.constants.CommonConstants;
/**
* 加密工具类
* @author 88397658
*
*/
public class EncryptUtils {
/**
* base64加密
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String byte2base64(byte [] bytes) throws UnsupportedEncodingException {
String encodeBase64 = Base64.encode(bytes);
return encodeBase64;
}
/**
* 转为2进制
* @param str
* @param encode
* @return
* @throws IOException
*/
@SuppressWarnings("restriction")
public static byte [] base642byte(String str) throws IOException {
BASE64Decoder base64Decoder = new BASE64Decoder();
return base64Decoder.decodeBuffer(str);
}
/**
* base64加密 sun.misc.BASE64Decoder
* 与apache的base64不同,,因为其带有换行的,\r|\n
* @param str
* @param encode
* @return
* @throws IOException
*/
@SuppressWarnings("restriction")
public static String base64EncoderSun(byte [] bytes) throws IOException {
BASE64Encoder base64Eecoder = new BASE64Encoder();
return base64Eecoder.encode(bytes);
}
/**
* 解密
* BASE64 解密
* @param s
* @return
* @throws WSSecurityException
* @throws UnsupportedEncodingException
*/
public static String getFromBase64(String s) throws WSSecurityException, UnsupportedEncodingException {
return new String(Base64.decode(s),CommonConstants.GBK);
}
/**
* MD5 生成摘要
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String MD5Encode(String str) throws UnsupportedEncodingException{
return DigestUtils.md5Hex(str.getBytes(CommonConstants.GBK));
}
/**
* MD5 生成摘要
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String MD5Encode(String str,String encode) throws UnsupportedEncodingException{
return DigestUtils.md5Hex(str.getBytes(encode));
}
/**
* MD5 生成摘要 二进制
* @param str
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static byte[] MD5EncodeByte(byte[] b) throws UnsupportedEncodingException, NoSuchAlgorithmException{
MessageDigest instance = MessageDigest.getInstance("MD5");
return instance.digest(b);
}
/**
* SHA256 生成摘要 默认是2进制转为16进制的 并且是小写的
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String SHA256Encode(String str,String encode) throws UnsupportedEncodingException{
return DigestUtils.sha256Hex(str.getBytes(encode));
}
/**
* SHA160 生成摘要 二进制
* @param str
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static byte[] SHAByte(byte[] b,String bit) throws UnsupportedEncodingException, NoSuchAlgorithmException{
MessageDigest instance = MessageDigest.getInstance(bit);
return instance.digest(b);
}
/**
* SHA256 生成摘要 2进制
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static byte[] SHA256EncodeH(String str,String encode) throws UnsupportedEncodingException, NoSuchAlgorithmException{
MessageDigest instance = MessageDigest.getInstance("SHA-256");
return instance.digest(str.getBytes(encode));
}
/**
* AES 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws Exception
*/
public static byte[] encryptAES(String content, String key) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
KeyGenerator kgen = KeyGenerator.getInstance(CommonConstants.AES);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 加解密保持同个随机种子
random.setSeed(key.getBytes());
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, CommonConstants.AES);
Cipher cipher = Cipher.getInstance(CommonConstants.AES);// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key1);// 初始化
byte[] result = cipher.doFinal(content.getBytes());
return result; // 加密
}
public static byte[] encryptAES(String content, String key,String encode) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
KeyGenerator kgen = KeyGenerator.getInstance(CommonConstants.AES);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 加解密保持同个随机种子
random.setSeed(key.getBytes());
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, CommonConstants.AES);
Cipher cipher = Cipher.getInstance(CommonConstants.AES);// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key1);// 初始化
byte[] result = cipher.doFinal(content.getBytes(encode));
return result; // 加密
}
/**
* AES 解密
*
* @param content 待解密内容
* @param password 解密密钥
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] decryptAES(byte[] content, String password) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
KeyGenerator kgen = KeyGenerator.getInstance(CommonConstants.AES);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");// 加解密保持同个随机种子
random.setSeed(password.getBytes());
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, CommonConstants.AES);
Cipher cipher = Cipher.getInstance(CommonConstants.AES);// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws Exception
*/
public static byte[] encryptDES(String data, String key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
// String strs = new BASE64Encoder().encode(bt);
return bt;
}
/**
* 指定字符编码方式并加密
* @param data
* @param key
* @param encoding
* @return
* @throws UnsupportedEncodingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws Exception
*/
public static byte[] encryptDES(String data, String key, String encoding) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] bt = encrypt(data.getBytes(encoding), key.getBytes());
// String strs = new BASE64Encoder().encode(bt);
return bt;
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws IOException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws Exception
*/
public static String decryptDES(String data, String key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
if (data == null)
return null;
// BASE64Decoder decoder = new BASE64Decoder();
// byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(data.getBytes(), key.getBytes());
return new String(bt);
}
/**
* 根据键值解密并返回指定编码方式字符串
* @param data
* @param key
* @param encoding
* @return
* @throws IOException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws Exception
*/
public static byte[] decryptDES(byte[] data, String key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return decrypt(data, key.getBytes());
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CommonConstants.DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(CommonConstants.DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CommonConstants.DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(CommonConstants.DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* 生成钥匙对
* @throws NoSuchAlgorithmException
*/
public static KeyPair getKeyPair() throws NoSuchAlgorithmException{
//使用KeyPairGenerator生成器来生成keyPair对象
KeyPairGenerator pairGenerator = KeyPairGenerator.getInstance("RSA");
//初始位数 位数要大于等于512。越长,加密解密越慢,越安全
pairGenerator.initialize(512);
//生成钥匙对,包括公钥和私钥
KeyPair genKeyPair = pairGenerator.generateKeyPair();
return genKeyPair;
}
/**
* 返回公钥
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static PublicKey getPubKey(KeyPair keyPair) throws InvalidKeySpecException, NoSuchAlgorithmException{
PublicKey public1 = keyPair.getPublic();//获取公钥
byte[] encoded = public1.getEncoded();
//公钥需要转换成X509EncodedKeySpec,然后通过keyFactory来生成public对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey publicKey = factory.generatePublic(keySpec);
return publicKey;
}
/**
* 返回私钥
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static PrivateKey getPrivateKey(KeyPair keyPair) throws InvalidKeySpecException, NoSuchAlgorithmException{
PrivateKey private1 = keyPair.getPrivate();
byte[] encoded = private1.getEncoded();
//私钥需要转换成PKCS8EncodedKeySpec,然后通过factory来生成私钥对象
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(keySpec);
return privateKey;
}
/**
* 使用公钥加密
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] encryptPulicKey(String str,PublicKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(str.getBytes());
return doFinal;
}
/**
* 私钥解密
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static String decodePrivate(byte [] aa,PrivateKey key) throws IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(aa);
return new String(doFinal);
}
/**
* 使用私钥加密
* @param args
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static byte[] encryptPrivate(String str,PrivateKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
byte[] doFinal = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
doFinal = cipher.doFinal(str.getBytes());
return doFinal;
}
/**
* 使用公钥解密
* @param args
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static String decodePublicKey(byte[] b ,PublicKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
byte[] doFinal = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
doFinal = cipher.doFinal(b);
return new String(doFinal);
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将二进制转换成16进制 小写
*
* @param buf
* @return
*/
public static String parseByte2HexStrLower(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toLowerCase());
}
return sb.toString();
}
/**
* 转为大写
* @param args
* @throws Exception
*/
public static String toupperCase(String str){
return str.toUpperCase();
}
/**
* 转为小写
* @param args
* @throws Exception
*/
public static String toLowerCase(String str){
return str.toLowerCase();
}
/*public static EncryptType getEncryType(String val){
if(val.equals("BASE64")){
return EncryptType.CharHandleType.BASE64;
}else if(val.equals("")){
}
}*/
public static void main(String[] args) throws Exception {
String content = "1234注册56";
String password = "12dc293d43db3b237849";
/*// String base64 = base64Encode(content);
// 加密
System.out.println("加密前:" + content);
// System.out.println("加密前:" + base64);
String encryptResult = EncryptUtils.encryptDES(content, password);
System.out.println("加密后:" + encryptResult);
System.out.println("加111密后:" + encryptResult);
// 解密
String decryptResult = EncryptUtils.decryptDES(encryptResult, password);
//
// System.out.println("解密后:" + new String(decryptResult));
//
// String result = new String(decryptResult);
//
System.out.println("解密---》"+decryptResult);
String str = "1234注册56";
System.out.println("待RSA加密的字符串:"+str);
KeyPair keyPair = getKeyPair();//获取一对钥匙,包括公钥和私钥
PublicKey pubKey = getPubKey(keyPair);//获取公钥
//公钥加密
byte[] encryptPulicKey = encryptPulicKey(str, pubKey);
System.out.println("公钥加密后的:"+encryptPulicKey);
//获取私钥
PrivateKey privateKey = getPrivateKey(keyPair);
//私钥解密
String decodePrivate = decodePrivate(encryptPulicKey, privateKey);
System.out.println("私钥解密后:"+decodePrivate);
*//***************使用公钥解密 私钥加密**********************//*
String str1 = "十分放松放松";
KeyPair keyPair2 = getKeyPair();
System.out.println("待加密的文字:"+str1);
PrivateKey privateKey2 = getPrivateKey(keyPair2);
byte[] encryptPrivate = encryptPrivate(str1, privateKey2);
System.out.println("私钥加密后的:"+encryptPrivate);
PublicKey pubKey2 = getPubKey(keyPair2);
String decodePublicKey = decodePublicKey(encryptPrivate, pubKey2);
System.out.println("公钥解密后:"+decodePublicKey);
CharHandleType valueOf = EncryptType.CharHandleType.valueOf("BASE64");
System.out.println(valueOf);*/
password = "0123456789ABCDEF";
byte[] decryptAES = EncryptUtils.encryptAES(content, password);
String byte2base64 = EncryptUtils.byte2base64(decryptAES);
System.out.println("加密:"+byte2base64);
byte[] base642byte = EncryptUtils.base642byte(byte2base64);
byte[] decryptAES2 = EncryptUtils.decryptAES(base642byte, password);
System.out.println("解密:"+new String(decryptAES2));
}
}
680

被折叠的 条评论
为什么被折叠?



