C#.NET 国密SM4加密解密 CBC ECB 2种模式
注意点:
1。加密时,明文转 byte[] 时,不要用 Encoding.Default,一定要指定编码,如:UTF-8。 解密时,解出的 byte[] 转 string 同样要指定相同的编码。
2。algorithm,算法,双方要保持一致。
3。SM4有一个小问题:字符串的长度需要满足是16的倍数(>=1),所以要padding.
nuget引用了三方库:Portable.BouncyCastle,1.9.0 版本。
基础工具类GmUtil.cs:
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.IO; namespace CommonUtils
{
/**
* need lib:
* BouncyCastle.Crypto.dll(http://www.bouncycastle.org/csharp/index.html) * 用BC的注意点:
* 这个版本的BC对SM3withSM2的结果为asn1格式的r和s,如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
* 这个版本的BC对SM2的结果为C1||C2||C3,据说为旧标准,新标准为C1||C3||C2,用新标准的需要自己转换。下面(被注释掉的)changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2,csharp版没准以后也会加,但目前还没有,java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
*
* 按要求国密算法仅允许使用加密机,本demo国密算法仅供学习使用,请不要用于生产用途。
*/
public class GmUtil
{ //private static readonly ILog log = LogManager.GetLogger(typeof(GmUtil)); private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N); /**
*
* @param msg
* @param userId
* @param privateKey
* @return r||s,直接拼接byte数组的rs
*/
public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
} /**
* @param msg
* @param userId
* @param privateKey
* @return rs in <b>asn1 format</b>
*/
public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
{
try
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(true, new ParametersWithID(privateKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
byte[] sig = signer.GenerateSignature();
return sig;
}
catch (Exception e)
{
//log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
return null;
}
} /**
*
* @param msg
* @param userId
* @param rs r||s,直接拼接byte数组的rs
* @param publicKey
* @return
*/
public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
{
if (rs == null || msg == null || userId == null) return false;
if (rs.Length != RS_LEN * 2) return false;
return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
} /**
*
* @param msg
* @param userId
* @param rs in <b>asn1 format</b>
* @param publicKey
* @return
*/ public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
{
try
{
ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
signer.Init(false, new ParametersWithID(publicKey, userId));
signer.BlockUpdate(msg, 0, msg.Length);
return signer.VerifySignature(sign);
}
catch (Exception e)
{
//log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
return false;
}
} /**
* bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
* @param c1c2c3
* @return
*/
private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().getDigestSize();
byte[] result = new byte[c1c2c3.Length];
Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
return result;
} /**
* bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
* @param c1c3c2
* @return
*/
private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
{
int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
const int c3Len = 32; //new SM3Digest().GetDigestSize();
byte[] result = new byte[c1c3c2.Length];
Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
return result;
} /**
* c1||c3||c2
* @param data
* @param key
* @return
*/
public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
{
return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
} /**
* c1||c3||c2
* @param data
* @param key
* @return
*/ public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
{
return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
} /**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2EncryptOld error: " + e.Message, e);
return null;
}
} /**
* c1||c2||c3
* @param data
* @param key
* @return
*/
public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
{
try
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, key);
return sm2Engine.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
//log.Error("Sm2DecryptOld error: " + e.Message, e);
return null;
}
} /**
* @param bytes
* @return
*/
public static byte[] Sm3(byte[] bytes)
{
try
{
SM3Digest digest = new SM3Digest();
digest.BlockUpdate(bytes, 0, bytes.Length);
byte[] result = DigestUtilities.DoFinal(digest);
return result;
}
catch (Exception e)
{
//log.Error("Sm3 error: " + e.Message, e);
return null;
}
} private const int RS_LEN = 32; private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
{
// for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
// r and s are the result of mod n, so they should be less than n and have length<=32
byte[] rs = rOrS.ToByteArray();
if (rs.Length == RS_LEN) return rs;
else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
else if (rs.Length < RS_LEN)
{
byte[] result = new byte[RS_LEN];
Arrays.Fill(result, (byte)0);
Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
return result;
}
else
{
throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
}
} /**
* BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
* @param rsDer rs in asn1 format
* @return sign result in plain byte array
*/
private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
{
Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
byte[] result = new byte[RS_LEN * 2];
Buffer.BlockCopy(r, 0, result, 0, r.Length);
Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
return result;
} /**
* BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
* @param sign in plain byte array
* @return rs result in asn1 format
*/
private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
{
if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
Asn1EncodableVector v = new Asn1EncodableVector();
v.Add(new DerInteger(r));
v.Add(new DerInteger(s));
try
{
return new DerSequence(v).GetEncoded("DER");
}
catch (IOException e)
{
//log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
return null;
}
} public static AsymmetricCipherKeyPair GenerateKeyPair()
{
try
{
ECKeyPairGenerator kpGen = new ECKeyPairGenerator();
kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
return kpGen.GenerateKeyPair();
}
catch (Exception e)
{
//log.Error("generateKeyPair error: " + e.Message, e);
return null;
}
} public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
{
return new ECPrivateKeyParameters(d, ecDomainParameters);
} public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
{
return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
} public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
{ FileStream fileStream = null;
try
{
//file.DirectoryName + "\\" + file.Name
fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
return certificate.GetPublicKey();
}
catch (Exception e)
{
//log.Error(file.Name + "读取失败,异常:" + e);
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return null;
} public class Sm2Cert
{
public AsymmetricKeyParameter privateKey;
public AsymmetricKeyParameter publicKey;
public String certId;
} private static byte[] ToByteArray(int i)
{
byte[] byteArray = new byte[4];
byteArray[0] = (byte)(i >> 24);
byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
byteArray[2] = (byte)((i & 0xFFFF) >> 8);
byteArray[3] = (byte)(i & 0xFF);
return byteArray;
} /**
* 字节数组拼接
*
* @param params
* @return
*/
private static byte[] Join(params byte[][] byteArrays)
{
List<byte> byteSource = new List<byte>();
for (int i = 0; i < byteArrays.Length; i++)
{
byteSource.AddRange(byteArrays[i]);
}
byte[] data = byteSource.ToArray();
return data;
} /**
* 密钥派生函数
*
* @param Z
* @param klen
* 生成klen字节数长度的密钥
* @return
*/
private static byte[] KDF(byte[] Z, int klen)
{
int ct = 1;
int end = (int)Math.Ceiling(klen * 1.0 / 32);
List<byte> byteSource = new List<byte>();
try
{
for (int i = 1; i < end; i++)
{
byteSource.AddRange(GmUtil.Sm3(Join(Z, ToByteArray(ct))));
ct++;
}
byte[] last = GmUtil.Sm3(Join(Z, ToByteArray(ct)));
if (klen % 32 == 0)
{
byteSource.AddRange(last);
}
else
byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
return byteSource.ToArray();
}
catch (Exception e)
{
//log.Error("KDF error: " + e.Message, e);
}
return null;
} public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, String algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(false, new ParametersWithIV(key, iv));
return c.DoFinal(cipher);
}
catch (Exception e)
{
//log.Error("Sm4DecryptCBC error: " + e.Message, e);
return null;
}
} public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, String algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
if (iv == null) iv = ZeroIv(algo);
c.Init(true, new ParametersWithIV(key, iv));
return c.DoFinal(plain);
}
catch (Exception e)
{
//log.Error("Sm4EncryptCBC error: " + e.Message, e);
return null;
}
} public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (plain.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(true, key);
return c.DoFinal(plain);
}
catch (Exception e)
{
//log.Error("Sm4EncryptECB error: " + e.Message, e);
return null;
}
} public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
{
if (keyBytes.Length != 16) throw new ArgumentException("err key length");
if (cipher.Length % 16 != 0) throw new ArgumentException("err data length"); try
{
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
IBufferedCipher c = CipherUtilities.GetCipher(algo);
c.Init(false, key);
return c.DoFinal(cipher);
}
catch (Exception e)
{
//log.Error("Sm4DecryptECB error: " + e.Message, e);
return null;
}
} public const String SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
public const String SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
public const String SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding"; /**
* cfca官网CSP沙箱导出的sm2文件
* @param pem 二进制原文
* @param pwd 密码
* @return
*/
public static Sm2Cert readSm2File(byte[] pem, String pwd)
{ Sm2Cert sm2Cert = new Sm2Cert();
try
{
Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
// ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert // ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
// ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
byte[] key = KDF(System.Text.Encoding.UTF8.GetBytes(pwd), 32);
byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
priKeyAsn1.GetOctets(),
Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
// log.Info(Hex.toHexString(priKeyD)); // ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
X509Certificate x509 = (X509Certificate)new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
return sm2Cert;
}
catch (Exception e)
{
//log.Error("readSm2File error: " + e.Message, e);
return null;
}
} /**
*
* @param cert
* @return
*/
public static Sm2Cert ReadSm2X509Cert(byte[] cert)
{
Sm2Cert sm2Cert = new Sm2Cert();
try
{ X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
sm2Cert.publicKey = x509.GetPublicKey();
sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
return sm2Cert;
}
catch (Exception e)
{
//log.Error("ReadSm2X509Cert error: " + e.Message, e);
return null;
}
} public static byte[] ZeroIv(String algo)
{ try
{
IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
int blockSize = cipher.GetBlockSize();
byte[] iv = new byte[blockSize];
Arrays.Fill(iv, (byte)0);
return iv;
}
catch (Exception e)
{
//log.Error("ZeroIv error: " + e.Message, e);
return null;
}
} public static void Main2(string[] s)
{ // 随便看看
//log.Info("GMNamedCurves: ");
foreach (string e in GMNamedCurves.Names)
{
//log.Info(e);
}
//log.Info("sm2p256v1 n:" + x9ECParameters.N);
//log.Info("sm2p256v1 nHex:" + Hex.ToHexString(x9ECParameters.N.ToByteArray())); // 生成公私钥对 ---------------------
AsymmetricCipherKeyPair kp = GmUtil.GenerateKeyPair();
//log.Info("private key d: " + ((ECPrivateKeyParameters)kp.Private).D);
//log.Info("public key q:" + ((ECPublicKeyParameters)kp.Public).Q); //{x, y, zs...} //签名验签
byte[] msg = System.Text.Encoding.UTF8.GetBytes("message digest");
byte[] userId = System.Text.Encoding.UTF8.GetBytes("userId");
byte[] sig = SignSm3WithSm2(msg, userId, kp.Private);
//log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
//log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, kp.Public)); // 由d生成私钥 ---------------------
BigInteger d = new BigInteger("097b5230ef27c7df0fa768289d13ad4e8a96266f0fcb8de40d5942af4293a54a", 16);
ECPrivateKeyParameters bcecPrivateKey = GetPrivatekeyFromD(d);
//log.Info("testGetFromD: " + bcecPrivateKey.D.ToString(16)); //公钥X坐标PublicKeyXHex: 59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4
//公钥Y坐标PublicKeyYHex: 9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8
AsymmetricKeyParameter publicKey = GetPublickeyFromX509File(new FileInfo("d:/certs/69629141652.cer"));
//log.Info(publicKey);
AsymmetricKeyParameter publicKey1 = GetPublickeyFromXY(new BigInteger("59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4", 16), new BigInteger("9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8", 16));
//log.Info("testReadFromX509File: " + ((ECPublicKeyParameters)publicKey).Q);
//log.Info("testGetFromXY: " + ((ECPublicKeyParameters)publicKey1).Q);
//log.Info("testPubKey: " + publicKey.Equals(publicKey1));
//log.Info("testPubKey: " + ((ECPublicKeyParameters)publicKey).Q.Equals(((ECPublicKeyParameters)publicKey1).Q)); // sm2 encrypt and decrypt test ---------------------
AsymmetricCipherKeyPair kp2 = GenerateKeyPair();
AsymmetricKeyParameter publicKey2 = kp2.Public;
AsymmetricKeyParameter privateKey2 = kp2.Private;
byte[] bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), publicKey2);
//log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
bs = Sm2Decrypt(bs, privateKey2);
//log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs)); // sm4 encrypt and decrypt test ---------------------
//0123456789abcdeffedcba9876543210 + 0123456789abcdeffedcba9876543210 -> 681edf34d206965e86b3e94f536e4246
byte[] plain = Hex.Decode("0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210");
byte[] key = Hex.Decode("0123456789abcdeffedcba9876543210");
byte[] cipher = Hex.Decode("595298c7c6fd271f0402f804c33d3f66");
bs = Sm4EncryptECB(key, plain, GmUtil.SM4_ECB_NOPADDING);
//log.Info("testSm4EncEcb: " + Hex.ToHexString(bs)); ;
bs = Sm4DecryptECB(key, bs, GmUtil.SM4_ECB_NOPADDING);
//log.Info("testSm4DecEcb: " + Hex.ToHexString(bs)); //读.sm2文件
String sm2 = "MIIDHQIBATBHBgoqgRzPVQYBBAIBBgcqgRzPVQFoBDDW5/I9kZhObxXE9Vh1CzHdZhIhxn+3byBU\nUrzmGRKbDRMgI3hJKdvpqWkM5G4LNcIwggLNBgoqgRzPVQYBBAIBBIICvTCCArkwggJdoAMCAQIC\nBRA2QSlgMAwGCCqBHM9VAYN1BQAwXDELMAkGA1UEBhMCQ04xMDAuBgNVBAoMJ0NoaW5hIEZpbmFu\nY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEbMBkGA1UEAwwSQ0ZDQSBURVNUIFNNMiBPQ0Ex\nMB4XDTE4MTEyNjEwMTQxNVoXDTIwMTEyNjEwMTQxNVowcjELMAkGA1UEBhMCY24xEjAQBgNVBAoM\nCUNGQ0EgT0NBMTEOMAwGA1UECwwFQ1VQUkExFDASBgNVBAsMC0VudGVycHJpc2VzMSkwJwYDVQQD\nDCAwNDFAWnRlc3RAMDAwMTAwMDA6U0lHTkAwMDAwMDAwMTBZMBMGByqGSM49AgEGCCqBHM9VAYIt\nA0IABDRNKhvnjaMUShsM4MJ330WhyOwpZEHoAGfqxFGX+rcL9x069dyrmiF3+2ezwSNh1/6YqfFZ\nX9koM9zE5RG4USmjgfMwgfAwHwYDVR0jBBgwFoAUa/4Y2o9COqa4bbMuiIM6NKLBMOEwSAYDVR0g\nBEEwPzA9BghggRyG7yoBATAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3Vz\nL3VzLTE0Lmh0bTA4BgNVHR8EMTAvMC2gK6AphidodHRwOi8vdWNybC5jZmNhLmNvbS5jbi9TTTIv\nY3JsNDI4NS5jcmwwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBREhx9VlDdMIdIbhAxKnGhPx8FcHDAd\nBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDAYIKoEcz1UBg3UFAANIADBFAiEAgWvQi3h6\niW4jgF4huuXfhWInJmTTYr2EIAdG8V4M8fYCIBixygdmfPL9szcK2pzCYmIb6CBzo5SMv50Odycc\nVfY6";
bs = Convert.FromBase64String(sm2);
String pwd = "cfca1234";
GmUtil.Sm2Cert sm2Cert = GmUtil.readSm2File(bs, pwd);
//log.Info("testReadSm2File, pubkey: " + ((ECPublicKeyParameters)sm2Cert.publicKey).Q.ToString());
//log.Info("testReadSm2File, prikey: " + Hex.ToHexString(((ECPrivateKeyParameters)sm2Cert.privateKey).D.ToByteArray()));
//log.Info("testReadSm2File, certId: " + sm2Cert.certId); bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), ((ECPublicKeyParameters)sm2Cert.publicKey));
//log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
bs = Sm2Decrypt(bs, ((ECPrivateKeyParameters)sm2Cert.privateKey));
//log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs)); msg = System.Text.Encoding.UTF8.GetBytes("message digest");
userId = System.Text.Encoding.UTF8.GetBytes("userId");
sig = SignSm3WithSm2(msg, userId, ((ECPrivateKeyParameters)sm2Cert.privateKey));
//log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
//log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, ((ECPublicKeyParameters)sm2Cert.publicKey)));
} }
}
使用加解密:
using CommonUtils;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace 国密SM4加密
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } string _Key = "9814548961710661";//密钥长度必须为16字节。
string _Iv = "0000000000000000"; /// <summary>
/// SM4 ECB 加密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSm4EcbEncrypt_Click(object sender, EventArgs e)
{
string algo = "SM4/ECB/NoPadding"; byte[] keyBytes = Encoding.UTF8.GetBytes(_Key);
//SM4有一个小问题:字符串的长度需要满足是16的倍数(>=1),所以要padding.
//加密前需要padding
byte[] plain = MyPadding(Encoding.UTF8.GetBytes(txt明文.Text), 1);
byte[] byRst = GmUtil.Sm4EncryptECB(keyBytes, plain, algo);
string result2 = Encoding.UTF8.GetString(Hex.Encode(byRst)); txt密文.Text = result2;
} /// <summary>
/// SM4 ECB 解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSm4EcbDecrypt_Click(object sender, EventArgs e)
{
string algo = "SM4/ECB/NoPadding"; byte[] keyBytes = Encoding.UTF8.GetBytes(_Key);
byte[] plain = Hex.Decode(txt密文.Text);
byte[] byRst = GmUtil.Sm4DecryptECB(keyBytes, plain, algo);
//解密后需要移除padding
byte[] plain2 = MyPadding(byRst, 0);
string result2 = Encoding.UTF8.GetString(plain2); txt解密后明文.Text = result2;
} /// <summary>
/// 补足 16 进制字符串的 0 字符,返回不带 0x 的16进制字符串
/// </summary>
/// <param name="input"></param>
/// <param name="mode">1表示加密,0表示解密</param>
/// <returns></returns>
private static byte[] MyPadding(byte[] input, int mode)
{
if (input == null)
{
return null;
}
byte[] ret = (byte[])null;
if (mode == 1)
{
int p = 16 - input.Length % 16;
ret = new byte[input.Length + p];
Array.Copy(input, 0, ret, 0, input.Length);
for (int i = 0; i < p; i++)
{
ret[input.Length + i] = (byte)p;
}
}
else
{
int p = input[input.Length - 1];
ret = new byte[input.Length - p];
Array.Copy(input, 0, ret, 0, input.Length - p);
}
return ret;
} /// <summary>
/// SM4 CBC 加密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSm4CbcEncrypt_Click(object sender, EventArgs e)
{
//algorithm
string algo = "SM4/CBC/PKCS7Padding";
//algo = "SM4/CBC/NoPadding"; byte[] keyBytes = Encoding.UTF8.GetBytes(_Key);
byte[] ivBytes = Encoding.UTF8.GetBytes(_Iv); //加密前需要padding
byte[] plain = MyPadding(Encoding.UTF8.GetBytes(txt明文.Text), 1);
byte[] byRst = GmUtil.Sm4EncryptCBC(keyBytes, plain, ivBytes, algo);
string result2 = Encoding.UTF8.GetString(Hex.Encode(byRst)); txt密文.Text = result2;
} /// <summary>
/// SM4 CBC 解密
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSm4CbcDecrypt_Click(object sender, EventArgs e)
{
string algo = "SM4/CBC/PKCS7Padding";
//algo = "SM4/CBC/NoPadding"; byte[] keyBytes = Encoding.UTF8.GetBytes(_Key);
byte[] ivBytes = Encoding.UTF8.GetBytes(_Iv); byte[] plain = Hex.Decode(txt密文.Text);
byte[] byRst = GmUtil.Sm4DecryptCBC(keyBytes, plain, ivBytes, algo);
//解密后需要移除padding
byte[] plain2 = MyPadding(byRst, 0);
string result2 = Encoding.UTF8.GetString(plain2); txt解密后明文.Text = result2;
}
}
}
MyPadding(byte[] input, int mode) 是补充16位的方法。
SM4/ECB/NoPadding + MyPadding() 方法相当于 JAVA BC 库里的 SM4/ECB/PKCS5Padding。
使用 SM4/ECB/PKCS5Padding 时就不需要MyPadding() 方法了。并且去除 “//if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");” 这个限制。
C#.NET 国密SM4加密解密 CBC ECB 2种模式的更多相关文章
- java sm4国密算法加密、解密
java sm4国密算法加密.解密 CreationTime--2018年7月5日09点20分 Author:Marydon 1.准备工作 所需jar包: bcprov-jdk15on-1.59. ...
- 一个关于国密SM4的故事
一个关于国密SM4的故事 我的名字叫SM4,我还有三位兄长,分别是大哥SM1, 二哥SM2, 和三哥SM3.说起我的名字,故事要回到2006年的时候,我出生的时候并不是叫SM4的,而是叫做SMS4.只 ...
- [转帖]一个关于国密SM4的故事
一个关于国密SM4的故事 https://www.cnblogs.com/ouyida3/p/10053862.html SM1 硬件SM2 非对称加密SM3 hash算法SM4 对称加密 一个关于国 ...
- 国密SM4对称算法实现说明(原SMS4无线局域网算法标准)
国密SM4对称算法实现说明(原SMS4无线局域网算法标准) SM4分组密码算法,原名SMS4,国家密码管理局于2012年3月21日发布:http://www.oscca.gov.cn/News/201 ...
- sm4加密 解密(oc)
前几天项目用到sm4加密解密,加密为十六进制字符串,再将十六进制字符串解密.网上百度了下,sm4是密钥长度和加密明文加密密文都为16个字节十六进制数据,网上的sm4 c语言算法很容易搜到,笔者刚开始没 ...
- Android DES加密的CBC模式加密解密和ECB模式加密解密
DES加密共有四种模式:电子密码本模式(ECB).加密分组链接模式(CBC).加密反馈模式(CFB)和输出反馈模式(OFB). CBC模式加密: import java.security.Key; i ...
- C++调用openssl实现DES加密解密cbc模式 zeropadding填充方式 pkcs5padding填充方式 pkcs7padding填充方式
============================================== des cbc 加密 zeropadding填充方式 ======================= ...
- 国密SM4分组加密算法实现 (C++)
原博客 :http://blog.csdn.net/archimekai/article/details/53095993 密码学的一次课程设计,学习了SM4加密算法,目前应用于无线网安全. SM4分 ...
- JAVASCRIPT加密方法,JS加密解密综述(7种)
一:最简单的加密解密 对于JAVASCRIPT函数escape()和unescape()想必是比较了解啦(很多网页加密在用它们),分别是编码和解码字符串,比如例子代码 用escape()函数加密后变为 ...
- 使用Docker编译OpenResty支持国密ssl加密
编译环境 执行编译操作环境如下 #操作系统 CentOS Linux release 7.4.1708 (Core) #docker版本 Version: 19.03.5 编译过程 Dockerfil ...
随机推荐
- 力扣33(java&python)-搜索旋转排序数组(中等)
题目: 整数数组 nums 按升序排列,数组中的值 互不相同 . 在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 ...
- CSS选择器练习--餐厅选择
1.题目:Select the plates 答案:plate 1 <div class="table"> 2 <plate></plate> ...
- 多任务学习模型之ESMM介绍与实现
简介:本文介绍的是阿里巴巴团队发表在 SIGIR'2018 的论文<Entire Space Multi-Task Model: An Effective Approach for Estima ...
- 谈谈C++新标准带来的属性(Attribute)
简介: 从C++11开始,标准引入了一个新概念"属性(attribute)",本文将简单介绍一下目前在C++标准中已经添加的各个属性以及常用属性的具体应用. 作者 | 寒冬来源 | ...
- [FAQ] Truffle Deployer 合约传参问题: Invalid number of parameters for "undefined". Got 0 expected 1!
在使用 `truffle migrate` 时,如果合约的构造函数需要传参,而部署脚本里没有传的时候,就会报这个错. 未传参时: const Migrations = artifacts.requir ...
- 【LGR-170-Div.3】洛谷基础赛 #6 & Cfz Round 3 & Caféforces #2
这套题感觉质量很高,思维含量大概div.2? A.Battle \[x \equiv r(\bmod P) \] \[P \mid x - r \] 因此只有第一次操作是有效的. void solve ...
- 【GUI界面软件】快手评论区采集:自动采集10000多条,含二级评论、展开评论!
目录 一.背景说明 1.1 效果演示 1.2 演示视频 1.3 软件说明 二.代码讲解 2.1 爬虫采集模块 2.2 软件界面模块 2.3 日志模块 三.获取源码及软件 一.背景说明 1.1 效果演示 ...
- .Net 线程与锁
一台服务器能运行多少个线程,大致取决于CPU的管理能力.CPU负责线程的创建.协调.切换.销毁.暂停.唤醒.运行等.一个应用程序中,必须有一个进程维持应用程序的运行环境,一个进程可同时有多个线程协作处 ...
- centos 7 开启 httpd 服务和 80 端口
centos 7 开启 httpd 服务和 80 端口 yum install -y httpd systemctl start httpd firewall-cmd --add-service=ht ...
- linux-centos7.6-gpt-uefi安装
目录 linux-centos7.6-gpt-uefi安装 一.需要 二.环境 三.vm新建虚拟机系统环境 四.开始安装 linux-centos7.6-gpt-uefi安装 一.需要 安装的系统适用 ...