51 lines
1.4 KiB
C#
51 lines
1.4 KiB
C#
using System;
|
|
using System.Text;
|
|
using Org.BouncyCastle.Crypto.Engines;
|
|
using Org.BouncyCastle.Crypto.Parameters;
|
|
using Org.BouncyCastle.Utilities.Encoders;
|
|
using UnityEngine;
|
|
|
|
|
|
class SM4Example: MonoBehaviour
|
|
{
|
|
// SM4 加密
|
|
public static byte[] Encrypt(byte[] plainText, byte[] key)
|
|
{
|
|
var engine = new SM4Engine();
|
|
engine.Init(true, new KeyParameter(key)); // true 表示加密模式
|
|
byte[] encrypted = new byte[plainText.Length];
|
|
engine.ProcessBlock(plainText, 0, encrypted, 0);
|
|
return encrypted;
|
|
}
|
|
|
|
|
|
// SM4 解密
|
|
public static byte[] Decrypt(byte[] cipherText, byte[] key)
|
|
{
|
|
var engine = new SM4Engine();
|
|
engine.Init(false, new KeyParameter(key)); // false 表示解密模式
|
|
byte[] decrypted = new byte[cipherText.Length];
|
|
engine.ProcessBlock(cipherText, 0, decrypted, 0);
|
|
return decrypted;
|
|
}
|
|
|
|
|
|
|
|
|
|
void Start()
|
|
{
|
|
// 密钥和明文
|
|
byte[] key = Encoding.UTF8.GetBytes("1234567890abcdef"); // 128 位密钥 (16 字节)
|
|
byte[] plainText = Encoding.UTF8.GetBytes("111");
|
|
|
|
|
|
// 加密
|
|
byte[] encrypted = Encrypt(plainText, key);
|
|
Console.WriteLine("加密后的数据 (Hex): " + Hex.ToHexString(encrypted));
|
|
|
|
|
|
// 解密
|
|
byte[] decrypted = Decrypt(encrypted, key);
|
|
Console.WriteLine("解密后的数据: " + Encoding.UTF8.GetString(decrypted));
|
|
}
|
|
} |