首页 > 编程语言 >JAVA (Spring Boot)数据AES加密解密

JAVA (Spring Boot)数据AES加密解密

时间:2023-03-08 15:24:37浏览次数:41  
标签:AES sSrc return String Spring Boot import null

package com.example.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;import java.security.SecureRandom;import java.util.Base64;


@Configuration
public class Common {/**
     * AES 加密
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc) throws Exception {
        if (sSrc == null) {
            return null;
        }
        String sKey= "pccms";
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(sKey.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        return Base64.getMimeEncoder().encodeToString(encrypted);
    }

    /**
     * AES 解密
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc) throws Exception {
        if (sSrc == null) {
            return null;
        }
        try {
            String sKey= "pccms";
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(sKey.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            Base64.Decoder decoder=Base64.getMimeDecoder();
            byte[] encrypted1 = decoder.decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }public static void main(String[] args) throws Exception {
        // 需要加密的字串
        String cSrc = "15039946305";
        System.out.println(cSrc);
        // 加密
        String enString = Encrypt(cSrc);
        System.out.println("加密后的字串是:" + enString);
        // 解密
        String DeString = Decrypt(enString);
        System.out.println("解密后的字串是:" + DeString);
    }

}

 

package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.Article;
import com.example.entity.Category;
import com.example.entity.MyProps;
import com.example.service.ArticleService;
import com.example.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
public class Common {

/**
* 将时间戳转换为时间
* @param s 时间戳
* @param t 时间
* @return
*/
public static String stampToDate(int s,String t){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(t);
Date date = new Date((long) s*1000);
res = simpleDateFormat.format(date);
return res;
}

/**
* 将时间转换为时间戳
* @param s 时间
* @return 返回时间戳
* @throws ParseException
*/

public static int dateToStamp(String s) throws ParseException {

//设置时间模版
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
// res = String.valueOf(ts);
return (int)date.getTime();
}


/**
* 获取热门咨询
*/
@Autowired
ArticleService articleService;
public List<Article> getCateHotlist(String catid){
List<Article> hotList = articleService.queryArticleCatid(catid,"",9,null);
hotList.forEach(item -> {
item.setInputtimeDate(Common.stampToDate(item.getInputtime(),"yyyy-MM-dd"));
});
return hotList;
}

/**
* catid 当前栏目ID
* parentid 父级ID
* child 通过 catid 查询到是否是父级信息 0 不是 1 是父级
* 获取子级栏目信息
*/
@Autowired
CategoryService categoryService;
public List<Category> getCategoryCat(String catid){
Category infoCat = categoryService.queryCatyById(catid);
String parentid = infoCat.getParentid();
int child = infoCat.getChild();
//1.获取父级信息
Category parentidInfo = categoryService.queryCatyById(parentid);
if (parentidInfo==null && child==0){
return null;
}else{
// 栏目一级
if (child == 1){
// 通过栏目ID 获取子级a
List<Category> lists = categoryService.queryCatyParentid(catid);
return lists;
}else{
//通过父级ID 获取栏目
List<Category> lists = categoryService.queryCatyParentid(parentid);
return lists;
}
}
}


@Autowired
MyProps myProps;
/**
* 调用php 接口
* @param methodName
* @param paramDta
* @return
*/
public JSONObject getUrlJson(String methodName, JSONObject paramDta){
RestTemplate restTemplate = new RestTemplate();
paramDta.put("token",myProps.getPhpToken());
// System.out.println(paramDta);
JSONObject result= restTemplate.postForObject(myProps.getCalculatedPhpUrl()+"ajava/ajava/"+methodName, paramDta,JSONObject.class);
return result;
}

/**
* AES 加密
* @param sSrc
* @return
* @throws Exception
*/
public static String Encrypt(String sSrc) throws Exception {
if (sSrc == null) {
return null;
}
String sKey= "pccms";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(sKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return Base64.getMimeEncoder().encodeToString(encrypted);

}

/**
* AES 解密
* @param sSrc
* @return
* @throws Exception
*/
public static String Decrypt(String sSrc) throws Exception {
if (sSrc == null) {
return null;
}
try {
String sKey= "pccms";
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(sKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(enCodeFormat , "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
Base64.Decoder decoder=Base64.getMimeDecoder();
byte[] encrypted1 = decoder.decode(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
}




/**
* 汉字转化为Unicode编码
* @param CN 待转化的中文
* @return 返回unicode编码
*/
public static String CNToUnicode(String CN) {

try {
StringBuilder out = new StringBuilder();
//直接获取字符串的unicode二进制
byte[] bytes = CN.getBytes("unicode");
//然后将其byte转换成对应的16进制表示即可
for (int i = 0; i < bytes.length - 1; i += 2) {
out.append("\\u");
String str = Integer.toHexString(bytes[i + 1] & 0xff);
for (int j = str.length(); j < 2; j++) {
out.append("0");
}
String str1 = Integer.toHexString(bytes[i] & 0xff);
out.append(str1);
out.append(str);
}
return out.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}



/**
* unicode编码转换为中文
* @param unicodeStr 待转化的编码
* @return 返回中文
*/
public static String UnicodeToCN(String unicodeStr) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(unicodeStr);
char ch;
while (matcher.find()) {
String group = matcher.group(2);
ch = (char) Integer.parseInt(group, 16);
String group1 = matcher.group(1);
unicodeStr = unicodeStr.replace(group1, ch + "");
}

return unicodeStr.replace("\\", "").trim();
}





public static void main(String[] args) throws Exception {
// 需要加密的字串
String cSrc = "15039946305";
System.out.println(cSrc);
// 加密
String enString = Encrypt(cSrc);
System.out.println("加密后的字串是:" + enString);
// 解密
String DeString = Decrypt(enString);
System.out.println("解密后的字串是:" + DeString);
}

}

标签:AES,sSrc,return,String,Spring,Boot,import,null
From: https://www.cnblogs.com/xiangangXu1997/p/17192090.html

相关文章

  • spring的NumberFormat注解
    转载:https://blog.51cto.com/u_3631118/3121347https://blog.csdn.net/weixin_38192427/article/details/122270716spring除了@DateTimeFormat之外,还提供了一个@NumberFo......
  • springBoot集成mqtt
    springBoot集成mqtt目录springBoot集成mqtt简介下载启动springBoot集成mqtt结束简介EMQX是一款大规模可弹性伸缩的云原生分布式物联网MQTT消息服务器。作为全球最具扩......
  • [java]-JWT-什么是JWT-JWT整合sprigboot
    1.什么是JWT?JSONWebToken(JWT)isanopenstandard(RFC7519)thatdefinesacompactandself-containedwayforsecurelytransmittinginformationbetweenpa......
  • JeecgBoot 3.5.0 版本发布,开源的企业级低代码平台
    新版发布,祝女神节日快乐—低代码能力更强大,让程序猿少写code,有更多时间陪女神!项目介绍JeecgBoot是一款企业级的低代码平台!前后端分离架构SpringBoot2.x,SpringCloud,An......
  • Springboot基础知识(20)- spring-boot-starter-web | 基于 Gradle 的 Springboot Web 项
    SpringBoot是在Spring的基础上创建一款开源框架,它提供了spring-boot-starter-web(Web启动器)来为Web开发予以支持。spring-boot-starter-web为我们提供了嵌入的Se......
  • jeecg-boot中分页接口用自定义sql和list实现
    1、controller中@ApiOperation(value="分析仪工作状态和报警-3列-分页",notes="分析仪工作状态和报警状态-分页")@ApiImplicitParams({@ApiImpli......
  • 设计模式5——自定义Spring框架
    1、Spring核心功能结构Spring大约有20个模块,由1300多个不同的文件构成。这些模块可以分为:核心容器、AOP和设备支持、数据访问与集成、Web组件、通信报文和集成测试等。下......
  • springboot redis 发布与订阅
    发布与订阅Redis的发布与订阅功能可以让客户端通过广播方式,将消息(message)同时发送给可能存在的多个客户端,并且发送消息的客户端不需要知道接收消息的客户端的具体信息。......
  • Spring Boot + MybatisX = 王炸!!
    1.什么是MybatisX?MybatisX是一款基于IDEA的快速开发插件,方便在使用mybatis以及mybatis-plus开始时简化繁琐的重复操作,提高开发速率。2.使用MybatisX的好处节省大量......
  • Spring IOC
    1.SpringIoc 2Spring框架2.1Spring框架概念Spring是众多开源java项目中的一员,基于分层的javaEE应用一站式轻量级开源框架,主要核心是IOC(控制反转/依赖注入)与A......