首页 > 其他分享 >代码链接

代码链接

时间:2024-05-26 20:12:48浏览次数:17  
标签:加密 String 代码 static key import byte 链接

代码

  package cn.edu.nuc.article.util;
   
  import org.bouncycastle.crypto.digests.SM3Digest;
  import org.bouncycastle.util.encoders.Hex;
   
  import java.security.Security;
  import java.util.Arrays;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.Random;
   
  public class SM3SaltHelper {
  public static void main(String[] args) {
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
   
  // 原始数据
  byte[] data = "Hello, World!".getBytes();
   
  // 生成随机的盐值
  byte[] salt = generateSalt();
   
  // 将原始数据与盐值拼接
  byte[] dataWithSalt = concatBytes(data, salt);
   
  // 计算SM3哈希值
  byte[] hash = calculateHash(dataWithSalt);
   
  // 将盐值和哈希值转换为十六进制字符串
  String saltHex = bytesToHex(salt);
  String hashHex = bytesToHex(hash);
   
  System.out.println("Salt: " + saltHex);
  System.out.println("Hash: " + hashHex);
  }
   
  public static String encrypt(String paramStr,byte[] salt){
  Map<String,String> resultMap=new HashMap<>();
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  // 原始数据
  byte[] data = paramStr.getBytes();
   
  // 将原始数据与盐值拼接
  byte[] dataWithSalt = concatBytes(data, salt);
   
  // 计算SM3哈希值
  byte[] hash = calculateHash(dataWithSalt);
   
  // 将盐值和哈希值转换为十六进制字符串
  String hashHex = bytesToHex(hash);
  return hashHex;
  }
   
   
  public static String entryptSM3Password(String plainPassword) {
  byte[] bytesSalt = generateSalt();
  String sm3Password= encrypt(plainPassword,bytesSalt);
  return bytesToHex(bytesSalt)+sm3Password;
  }
   
  public static byte[] generateSalt() {
  byte[] salt = new byte[8];
  new Random().nextBytes(salt);
  return salt;
  }
   
  private static byte[] concatBytes(byte[] a, byte[] b) {
  byte[] result = Arrays.copyOf(a, a.length + b.length);
  System.arraycopy(b, 0, result, a.length, b.length);
  return result;
  }
   
  private static byte[] calculateHash(byte[] input) {
  SM3Digest digest = new SM3Digest();
  digest.update(input, 0, input.length);
  byte[] result = new byte[digest.getDigestSize()];
  digest.doFinal(result, 0);
  return result;
  }
   
  public static String bytesToHex(byte[] bytes) {
  return Hex.toHexString(bytes);
  }
   
  public static byte[] HexTobytes(String hexStr) {
   
  return Hex.decode(hexStr);
  }
   
   
   
   
  }
  package cn.edu.nuc.article.util;
   
  import cn.hutool.core.io.FileUtil;
  import cn.hutool.core.io.IoUtil;
  import org.bouncycastle.jce.provider.BouncyCastleProvider;
  import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
   
  import javax.crypto.Cipher;
  import javax.crypto.CipherInputStream;
  import javax.crypto.CipherOutputStream;
  import javax.crypto.NoSuchPaddingException;
  import javax.crypto.spec.IvParameterSpec;
  import javax.crypto.spec.SecretKeySpec;
  import java.io.*;
  import java.nio.charset.StandardCharsets;
  import java.nio.file.Files;
  import java.nio.file.Paths;
  import java.security.*;
  import java.util.Arrays;
  import java.util.Random;
   
  public class SM4Tools {
  private static final String name="SM4"; //算法名字
  private static final String transformation="SM4/CBC/PKCS5Padding"; //加密模式以及短快填充方式
  private static final String Default_iv="0123456789abcdef"; //加密使用的初始向量
   
  /**
  * 加载指定文件,对其进行加密,并将加密结果写入指定输出文件中
  * @param inputFile 要加密的输入文件路径
  * @param outputFile 加密后的输出文件路径
  * @param key 加密所需的密钥
  * @throws Exception 如果文件读取、加密或写入时出现错误,则抛出异常
  */
  public static void encodeFile(String inputFile, String outputFile, String key) throws Exception {
  // 读取输入文件中的所有字节
  byte [] inputBytes = Files.readAllBytes(Paths.get(inputFile));
  // 对输入字节数组进行加密
  byte [] encodeByte = encode(inputBytes, key.getBytes(StandardCharsets.UTF_8));
  // 将加密后的字节数组写入指定输出文件中
  Files.write(Paths.get(outputFile),encodeByte);
  System.out.println("File encoded successfully.");
  }
  /**
  * 使用指定的加密算法和密钥对给定的字节数组进行加密
  * @param inputByte 要加密的字节数组
  * @param key 加密所需的密钥
  * @return 加密后的字节数组
  * @throws Exception 如果加密时发生错误,则抛出异常
  */
  public static byte [] encode(byte [] inputByte, byte [] key) throws Exception {
  // 获取加密实例
  Cipher c = Cipher.getInstance(transformation);
  // 根据密钥的字节数组创建 SecretKeySpec
  SecretKeySpec secretKeySpec = new SecretKeySpec(key, name);
  // 创建 IvParameterSpec 对象,使用默认向量和字符集
  IvParameterSpec ivParameterSpec = new IvParameterSpec(Default_iv.getBytes(StandardCharsets.UTF_8));
  // 初始化加密实例
  c.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
  // 返回加密后的字节数组
  return c.doFinal(inputByte);
  }
   
  public static void decodeFile(String inputFilePath, String outputFilePath, String key) throws Exception {
  byte[] inputBytes = Files.readAllBytes(Paths.get(inputFilePath));
  byte[] decodeBytes = decode(inputBytes, key.getBytes(StandardCharsets.UTF_8));
  Files.write(Paths.get(outputFilePath), decodeBytes);
  System.out.println("File decode successfully.");
  }
   
   
   
  public static byte[] decode(byte[] inputBytes, byte[] key) throws Exception {
  Cipher cipher = Cipher.getInstance(transformation);
  SecretKeySpec secretKeySpec = new SecretKeySpec(key, name);
  IvParameterSpec ivParameterSpec = new IvParameterSpec(Default_iv.getBytes(StandardCharsets.UTF_8));
  cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
  return cipher.doFinal(inputBytes);
  }
   
  public static String generateRandomString(int length) {
  Random random = new Random();
  StringBuffer string = new StringBuffer();
   
  for (int i = 0; i < length; i++) {
  // 生成随机字符(可以根据需要调整范围)
  int randomChar = random.nextInt(91);
  if (randomChar >= 48 && randomChar <= 57 || // 数字0-9
  randomChar >= 65 && randomChar <= 90 || // 大写字母A-Z
  randomChar >= 97 && randomChar <= 122) { // 小写字母a-z
  string.append((char) randomChar);
  } else {
  i--; // 重新生成当前位置的字符
  }
  }
   
  return string.toString();
  }
   
  public static void main(String[] args) throws Exception {
  Security.addProvider(new BouncyCastleProvider());
  String inputFile="D:\\data\\test01.docx"; //需要加密的文件
  String enFile="D:\\data\\test01Encode.docx"; //加密后的文件
  String deFile="D:\\data\\test01Decode.docx"; //解密后的文件
  //String key="0123456789ABCDEF"; //加密密钥,注意必须是128bits,即16个字节
  String key= generateRandomString(16) ;
  System.out.println(key);
  encodeFile(inputFile,enFile,key);
  decodeFile(enFile,deFile,key);
   
   
  }
   
  }

标签:加密,String,代码,static,key,import,byte,链接
From: https://www.cnblogs.com/sjd-sr/p/18214213

相关文章

  • 【路径规划】基于遗传算法求解带时间窗容量限制的单配送中心多骑手外卖配送路径规划问
    研究背景:随着外卖业务的快速发展,如何合理安排多骑手的配送路径,减少配送时间和成本,成为外卖平台需要解决的重要问题。在实际操作中,骑手需要在一定的时间窗内完成配送,并且配送中心的配送能力也有限,因此需要考虑时间窗和容量限制的多骑手外卖配送路径规划问题。研究步骤:理解......
  • GitHub:源代码管理的利器
    在现代软件开发中,源代码管理工具已经成为开发者日常工作中不可或缺的一部分。而其中最受欢迎和广泛使用的工具之一就是GitHub。无论你是初学者还是经验丰富的开发者,GitHub都为你提供了一整套功能强大且灵活的工具,帮助你更高效地管理和协作开发项目。本文将介绍GitHub的基本功能、......
  • 动态执行JS-把字符串当做代码去执行
    使用eval将字符串当做代码来执行functionzhiXing(strCode){eval(strCode)}zhiXing("console.log('hello')")在控制台会输出:helloeval的简单介绍1,eval是同步代码2,eval()执行代码时,读取变量是当前作用域;他会先去找当前作用域中有没有这个值;如果有就获取,如果......
  • 风控图算法Graph Embedding(DeepWalk&Node2Vec)代码实现
    风控图算法GraphEmbedding(DeepWalk&Node2Vec)代码实现在上一篇中我们简单介绍了常用的GraphEmbedding算法,今天来对其中较为常用的两种算法——DeepWalk和Node2Vec进行python代码实现。文章目录风控图算法GraphEmbedding(DeepWalk&Node2Vec)代码实现一、KarateClub算......
  • 源代码管理工具——Github
    一、Github简介面向开源及私有软件项目的托管平台GitHub分为Git和Hub。Git只是一个命令行工具,一个分布式版本控制系统。正是它在背后管理和跟踪你的代码历史版本,好比一个时光机,让你在代码出错时不至于手忙脚乱,能快速回退之前的历史版本。而Hub是“中心“、”枢纽”的意思。G......
  • 【元胞自动机】基于元胞自动机模拟社会力模型解决人员疏散问题附Matlab代码
    【元胞自动机】基于元胞自动机模拟社会力模型解决人员疏散问题附Matlab代码首先,元胞自动机(CellularAutomata,简称CA)是一种离散动力系统,由一个规则化的网络组成,每个元胞根据自身状态和周围邻居元胞的状态更新自身状态。CA模型已被广泛应用于模拟各种复杂系统,包括人群......
  • 二叉树的基本功能(代码实现)
    1.二叉树的概念在对树的介绍一文中,有明确的介绍。如有兴趣可移步至:数据结构:树的介绍-CSDN博客2.二叉树的代码实现2.1二叉树的结构体typedefintBTDataType;typedefstructBinaryTreeNode{ BTDataTypedata; structBinaryTreeNode*left; structBinaryTreeNo......
  • 【SOC估计】基于扩展卡尔曼滤波器实现锂离子电池充电状态估计附matlab代码和报告
    SOC对于电池的安全管理和使用效率至关重要。扩展卡尔曼滤波器(ExtendedKalmanFilter,EKF)是一种常用的SOC估计方法,它可以基于电池电压、电流等可观测量,通过数学模型对SOC进行实时动态估计。下面是一个基于MATLAB的EKF实现锂电池SOC估计的示例代码:matlab%定义电池......
  • 代码随想录算法训练营第第18天 | 513.找树左下角的值 、112. 路径总和 、106.从中
    找树左下角的值本地递归偏难,反而迭代简单属于模板题,两种方法掌握一下题目链接/文章讲解/视频讲解:https://programmercarl.com/0513.找树左下角的值.html/***Definitionforabinarytreenode.*functionTreeNode(val,left,right){*this.val=(val===undef......
  • 源代码管理工具
    在通过比较Github和TFS之后我更加倾向于Github,所以接下来我选择重点介绍Github1.1介绍GitHub是一个面向开源及私有软件项目的托管平台,因为只支持Git作为唯一的版本库格式进行托管,故名GitHub。GitHub于2008年4月10日正式上线,除了Git代码仓库托管及基本的Web管理......