using Org.BouncyCastle.Utilities.Encoders; using System; namespace Cyberpipe.SM4 { public class SM4Utils { private static string secretKey = "45f3fabdf725985ba451b9640ea46ea7"; public static byte[] SM4Encrypt(byte[] plainBytes) { SM4_Context ctx = new SM4_Context(); ctx.isPadding = true; ctx.mode = SM4.SM4_ENCRYPT; byte[] keyBytes = Hex.Decode(secretKey); SM4 sm4 = new SM4(); sm4.sm4_setkey_enc(ctx, keyBytes); byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainBytes); return encrypted; } public static string SM4EncryptStr(string asciiStr) { byte[] encrypted = SM4Utils.SM4Encrypt(System.Text.Encoding.ASCII.GetBytes(asciiStr)); return Hex.ToHexString(encrypted); } public static string SM4Decrypt(byte[] cipherBytes) { SM4_Context ctx = new SM4_Context(); ctx.isPadding = true; ctx.mode = SM4.SM4_DECRYPT; byte[] keyBytes = Hex.Decode(secretKey); SM4 sm4 = new SM4(); sm4.sm4_setkey_dec(ctx, keyBytes); byte[] decrypted = sm4.sm4_crypt_ecb(ctx, cipherBytes); return Hex.ToHexString(decrypted); } } }