From b7c05407dcf01cd7c01fde0efdf2a6a0283d4016 Mon Sep 17 00:00:00 2001
From: rain <167982779@qq.com>
Date: Sat, 03 Aug 2024 17:50:22 +0800
Subject: [PATCH] Merge remote-tracking branch 'origin/ht-dev' into ht-dev
---
src/main/java/com/dji/sample/droneairport/utils/SM4Util.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 files changed, 57 insertions(+), 0 deletions(-)
diff --git a/src/main/java/com/dji/sample/droneairport/utils/SM4Util.java b/src/main/java/com/dji/sample/droneairport/utils/SM4Util.java
new file mode 100644
index 0000000..2312585
--- /dev/null
+++ b/src/main/java/com/dji/sample/droneairport/utils/SM4Util.java
@@ -0,0 +1,57 @@
+package com.dji.sample.droneairport.utils;
+
+import org.bouncycastle.crypto.engines.SM4Engine;
+import org.bouncycastle.crypto.params.KeyParameter;
+import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
+import org.bouncycastle.crypto.paddings.PKCS7Padding;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Base64;
+
+public class SM4Util {
+ public static String encrypt(byte[] key, byte[] input) {
+ PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new SM4Engine(), new PKCS7Padding());
+ cipher.init(true, new KeyParameter(key)); // ECB模式下不需要IV
+ byte[] output = new byte[cipher.getOutputSize(input.length)];
+ int length = cipher.processBytes(input, 0, input.length, output, 0);
+ try {
+ length += cipher.doFinal(output, length);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ String encoded = Base64.getEncoder().encodeToString(Arrays.copyOf(output, length));
+ return encoded;
+ }
+
+ public static byte[] decrypt(byte[] key, byte[] input) {
+ PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new SM4Engine(), new PKCS7Padding());
+ cipher.init(false, new KeyParameter(key)); // ECB模式下不需要IV
+ byte[] output = new byte[cipher.getOutputSize(input.length)];
+ int length = cipher.processBytes(input, 0, input.length, output, 0);
+ try {
+ length += cipher.doFinal(output, length);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return Arrays.copyOf(output, length);
+ }
+
+ public static void main(String[] args) {
+ byte[] key = "jsimjrby3wqb7dbq".getBytes(StandardCharsets.UTF_8); // 16字节密钥
+
+ // 原始明文
+ String plaintext = "hello";
+
+ System.out.println("Encoded: " + encrypt(key, plaintext.getBytes(StandardCharsets.UTF_8)));
+
+ // 解码并解密
+ byte[] decoded = Base64.getDecoder().decode(encrypt(key, plaintext.getBytes(StandardCharsets.UTF_8)));
+ byte[] decrypted = decrypt(key, decoded);
+
+ // 输出结果
+ System.out.println("Plaintext: " + plaintext);
+ System.out.println("Encrypted (Base64): " + encrypt(key, plaintext.getBytes(StandardCharsets.UTF_8)));
+ System.out.println("Decrypted: " + new String(decrypted, StandardCharsets.UTF_8));
+ }
+}
--
Gitblit v1.9.3