/// <summary> /// Encrypts a plain array of bytes using a public key /// </summary> /// <param name="publicKey">the public key used for encryption</param> /// <param name="plainBytes">the plain bytes to encrypt</param> /// <returns></returns> public byte[] EncryptBytes(byte[] publicKey, byte[] plainBytes) { var pubKey = (ECPublicKeyParameters)CreateAsymmetricKeyParameterFromPublicKeyInfo(publicKey); var pubKeyWithRandom = new ParametersWithRandom(pubKey, new SecureRandom()); cipher.Init(true, pubKeyWithRandom); return(cipher.ProcessBlock(plainBytes, 0, plainBytes.Length)); }
protected override ICryptoValue EncryptByPublicKeyInternal(ArraySegment <byte> originalBytes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!Key.IncludePublicKey()) { throw new ArgumentException("There is no PublicKey in current Sm2Key instance."); } // get public key var publicKey = Key.GetPublicKey(); var cipherParams = publicKey.Parameters; var parametersWithRandom = new ParametersWithRandom(cipherParams); // create a sm2 engine var engine = new SM2Engine(); // init engine.Init(true, parametersWithRandom); // encrypt var cipherBytes = engine.ProcessBlock(originalBytes.Array, originalBytes.Offset, originalBytes.Count); return(CreateCryptoValue(GetBytes(originalBytes), cipherBytes, CryptoMode.Encrypt)); }
/// <summary> /// sm2解密 /// </summary> /// <param name="privateKey">私钥</param> /// <param name= "cipherText">加密数据的密文</param> public string Sm2Decrypt(string privateKey, string cipherText) { m_Logger.Debug($"[SM2Utils]Sm2Decrypt=>privateKey:{privateKey}"); m_Logger.Debug($"[SM2Utils]Sm2Decrypt=>cipherText:{cipherText}"); if (string.IsNullOrWhiteSpace(privateKey)) { m_Logger.Debug("[Sm2Decrypt]PrivateKey is empty"); return(null); } if (string.IsNullOrWhiteSpace(cipherText)) { m_Logger.Debug("[Sm2Decrypt]cipherText is empty"); return(null); } BigInteger pri = new BigInteger(privateKey, 16); ECPrivateKeyParameters aPri = new ECPrivateKeyParameters(pri, domainParams); SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(false, aPri); byte[] cipherByte = Utils.HexStringToByteArray(cipherText); byte[] result = sm2Engine.ProcessBlock(cipherByte, 0, cipherByte.Length); m_Logger.Debug($"[SM2Utils]Sm2Decrypt=>Utils.ByteArrayToHexString(result):{Utils.ByteArrayToHexString(result)}"); m_Logger.Debug($"[SM2Utils]Sm2Decrypt=>Utils.ByteArrayToHexString(result).Length:{Utils.ByteArrayToHexString(result).Length}"); return(Utils.ByteArrayToHexString(result)); }
private void DoEngineTestF2m() { BigInteger SM2_ECC_A = new BigInteger("00", 16); BigInteger SM2_ECC_B = new BigInteger("E78BCD09746C202378A7E72B12BCE00266B9627ECB0B5A25367AD1AD4CC6242B", 16); BigInteger SM2_ECC_N = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBC972CF7E6B6F900945B3C6A0CF6161D", 16); BigInteger SM2_ECC_H = BigInteger.ValueOf(4); BigInteger SM2_ECC_GX = new BigInteger("00CDB9CA7F1E6B0441F658343F4B10297C0EF9B6491082400A62E7A7485735FADD", 16); BigInteger SM2_ECC_GY = new BigInteger("013DE74DA65951C4D76DC89220D5F7777A611B1C38BAE260B175951DC8060C2B3E", 16); ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N, SM2_ECC_H); ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new TestRandomBigInteger("56A270D17377AA9A367CFA82E46FA5267713A9B91101D0777B07FCE018C757EB", 16)); keyPairGenerator.Init(aKeyGenParams); AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair(); ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public; ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private; SM2Engine sm2Engine = new SM2Engine(); byte[] m = Strings.ToByteArray("encryption standard"); sm2Engine.Init(true, new ParametersWithRandom(aPub, new TestRandomBigInteger("6D3B497153E3E92524E5C122682DBDC8705062E20B917A5F8FCDB8EE4C66663D", 16))); byte[] enc = sm2Engine.ProcessBlock(m, 0, m.Length); IsTrue("f2m enc wrong", Arrays.AreEqual(Hex.Decode( "04019D23 6DDB3050 09AD52C5 1BB93270 9BD534D4 76FBB7B0 DF9542A8 A4D890A3" + "F2E100B2 3B938DC0 A94D1DF8 F42CF45D 2D6601BF 638C3D7D E75A29F0 2AFB7E45" + "E91771FD 55AC6213 C2A8A040 E4CAB5B2 6A9CFCDA 737373A4 8625D375 8FA37B3E" + "AB80E9CF CABA665E 3199EA15 A1FA8189 D96F5791 25E4"), enc)); sm2Engine.Init(false, aPriv); byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); IsTrue("f2m dec wrong", Arrays.AreEqual(m, dec)); }
public byte[] Encrypt(string s, ECPublicKeyParameters aPub) { var sm2Engine = new SM2Engine(); var m = Strings.ToByteArray(s); sm2Engine.Init(true, new ParametersWithRandom(aPub, new SecureRandom())); return(sm2Engine.ProcessBlock(m, 0, m.Length)); }
public string Decrypt(byte[] enc, ECPrivateKeyParameters aPriv) { var sm2Engine = new SM2Engine(); sm2Engine.Init(false, aPriv); var dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); return(Strings.FromByteArray(dec)); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Decrypt(byte[] data) { if (mode == SM2Mode.C1C3C2) { data = C132ToC123(data); } var sm2 = new SM2Engine(new SM3()); sm2.Init(false, key.PrivateKeyParameters); return(sm2.ProcessBlock(data, 0, data.Length)); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] Encrypt(byte[] data) { var sm2 = new SM2Engine(new SM3()); sm2.Init(true, new ParametersWithRandom(key.PublicKeyParameters)); data = sm2.ProcessBlock(data, 0, data.Length); if (mode == SM2Mode.C1C3C2) { data = C123ToC132(data); } return(data); }
/** * sm2加密 * */ public static byte[] Encrypt(byte[] pubkey, byte[] srcData) { X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1"); SecureRandom random = new SecureRandom(); ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N); ECPublicKeyParameters pubKeyParameters = new ECPublicKeyParameters(sm2p256v1.Curve.DecodePoint(pubkey), parameters); SM2Engine engine = new SM2Engine(); ParametersWithRandom pwr = new ParametersWithRandom(pubKeyParameters, new SecureRandom()); engine.Init(true, pwr); return(encodeSM2CipherToDER(engine.ProcessBlock(srcData, 0, srcData.Length))); }
/** * sm2解密 */ public static byte[] Decrypt(byte[] privkey, byte[] srcData) { X9ECParameters sm2p256v1 = GMNamedCurves.GetByName("sm2p256v1"); SecureRandom random = new SecureRandom(); ECDomainParameters parameters = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N); ECPrivateKeyParameters priKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privkey), parameters); SM2Engine engine = new SM2Engine(); ParametersWithRandom pwr = new ParametersWithRandom(priKeyParameters, new SecureRandom()); engine.Init(false, priKeyParameters); byte[] c1c2c3 = decodeDERSM2Cipher(srcData); return(engine.ProcessBlock(c1c2c3, 0, c1c2c3.Length)); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); //byte[] bpfx = File.ReadAllBytes("~\\..\\..\\..\\..\\certificate.pfx"); ////Console.WriteLine(bpfx); //X509Certificate2 x5092 = new X509Certificate2(bpfx,"",X509KeyStorageFlags.Exportable); //RSA rsaPublicKey = (RSA)x5092.PublicKey.Key; byte[] b1 = File.ReadAllBytes("~\\..\\..\\..\\..\\rajat.txt"); //byte[] encryptedValue = rsaPublicKey.Encrypt(b1,RSAEncryptionPadding.Pkcs1); //RSA rsaPrivateKey = (RSA)x5092.PrivateKey; //if (File.Exists(("~\\..\\..\\..\\..\\exported_txt.txt"))) //{ // File.Delete("~\\..\\..\\..\\..\\exported_txt.txt"); //} //File.WriteAllBytes("~\\..\\..\\..\\..\\exported_txt.txt", rsaPrivateKey.Decrypt(encryptedValue, RSAEncryptionPadding.Pkcs1)); Program ps = new Program(); var keyPair = ps.GetKeyPair(); SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(true, new ParametersWithRandom((ECKeyParameters)keyPair.Public, new SecureRandom())); byte[] enc1 = sm2Engine.ProcessBlock(b1, 0, b1.Length); //System.out.println("Cipher Text (SM2Engine): " + Hex.toHexString(enc1)); sm2Engine = new SM2Engine(); sm2Engine.Init(false, (ECKeyParameters)keyPair.Private); byte[] dec1 = sm2Engine.ProcessBlock(enc1, 0, enc1.Length); //System.out.println("Plain Text (SM2Engine): " + Hex.toHexString(dec1)); if (File.Exists(("~\\..\\..\\..\\..\\exported_txt.txt"))) { File.Delete("~\\..\\..\\..\\..\\exported_txt.txt"); } File.WriteAllBytes("~\\..\\..\\..\\..\\exported_txt.txt", dec1); }
protected override string DoDecrypt(string cipherTextBase64, string charset, string privateKey) { //加载私钥参数 ICipherParameters cipherParams = BuildPrivateKeyParams(privateKey).Parameters; //初始化SM2算法引擎 SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(false, cipherParams); //对输入密文进行解密 byte[] input = Convert.FromBase64String(cipherTextBase64); byte[] output = sm2Engine.ProcessBlock(input, 0, input.Length); //将解密后的明文按指定字符集编码后返回 return(Encoding.GetEncoding(charset).GetString(output)); }
protected override string DoEncrypt(string plainText, string charset, string publicKey) { //加载公钥参数 ICipherParameters cipherParams = BuildPublickKeyParams(publicKey).Parameters; ParametersWithRandom parametersWithRandom = new ParametersWithRandom(cipherParams); //初始化SM2算法引擎 SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(true, parametersWithRandom); //对输入明文进行加密 byte[] input = Encoding.GetEncoding(charset).GetBytes(plainText); byte[] output = sm2Engine.ProcessBlock(input, 0, input.Length); //将密文Base64编码后返回 return(Convert.ToBase64String(output)); }
/// <summary> /// SM2解密 /// </summary> /// <param name="privateKey">私钥</param> /// <param name="cipherData">密文</param> /// <returns></returns> public static string Decrypt(string privateKey, string cipherData) { byte[] cipherDataByte = Hex.Decode(cipherData); //获取一条SM2曲线参数 X9ECParameters sm2EcParameters = GMNamedCurves.GetByName("sm2p256v1"); //构造domain参数 ECDomainParameters domainParameters = new ECDomainParameters(sm2EcParameters.Curve, sm2EcParameters.G, sm2EcParameters.N); BigInteger privateKeyD = new BigInteger(privateKey, 16); ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters); SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(false, privateKeyParameters); byte[] arrayOfBytes = sm2Engine.ProcessBlock(cipherDataByte, 0, cipherDataByte.Length); return(Encoding.UTF8.GetString(arrayOfBytes)); }
/// <summary> /// SM2加密 /// </summary> /// <param name="publicKey">公钥</param> /// <param name="data">明文</param> /// <returns>密文</returns> public static string Encrypt(string publicKey, string data) { // 获取一条SM2曲线参数 X9ECParameters sm2EcParameters = GMNamedCurves.GetByName("sm2p256v1"); // 构造domain参数 ECDomainParameters domainParameters = new ECDomainParameters(sm2EcParameters.Curve, sm2EcParameters.G, sm2EcParameters.N); //提取公钥点 ECPoint pukPoint = sm2EcParameters.Curve.DecodePoint(Hex.Decode(publicKey)); // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04 ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters); SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom())); byte[] input = Encoding.UTF8.GetBytes(data); byte[] arrayOfBytes = sm2Engine.ProcessBlock(input, 0, input.Length); return(Hex.ToHexString(arrayOfBytes)); }
protected override ICryptoValue DecryptByPrivateKeyInternal(ArraySegment <byte> cipherBytes, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!Key.IncludePrivateKey()) { throw new ArgumentException("There is no PrivateKey in current Sm2Key instance."); } // get private key var privateKey = Key.GetPrivateKey(); var cipherParams = privateKey.Parameters; // create a sm2 engine var engine = new SM2Engine(); // init engine.Init(false, cipherParams); // decrypt var originalBytes = engine.ProcessBlock(cipherBytes.Array, cipherBytes.Offset, cipherBytes.Count); return(CreateCryptoValue(originalBytes, GetBytes(cipherBytes), CryptoMode.Decrypt)); }
/// <summary> /// sm2加密 /// </summary> /// <param name="publicKey">公钥</param> /// <param name= "plainText">加密数据的明文</param> public string Sm2Encrypt(string publicKey, string plainText) { m_Logger.Debug($"[SM2Utils]Sm2Encrypt=>publicKey:{publicKey}"); m_Logger.Debug($"[SM2Utils]Sm2Encrypt=>plainText:{plainText}"); if (string.IsNullOrWhiteSpace(publicKey)) { m_Logger.Debug("[Sm2Encrypt]PublicKey is empty"); return(null); } if (string.IsNullOrWhiteSpace(plainText)) { m_Logger.Debug("[Sm2Encrypt]plainText is empty"); return(null); } var data = Utils.HexStringToByteArray(plainText); if (publicKey.StartsWith("04")) { publicKey = publicKey.Substring(2); } BigInteger x = new BigInteger(publicKey.Substring(0, 64), 16); BigInteger y = new BigInteger(publicKey.Substring(64), 16); ECPoint point = curve.CreatePoint(x, y); ECPublicKeyParameters aPub = new ECPublicKeyParameters(point, domainParams); SM2Engine sm2Engine = new SM2Engine(); sm2Engine.Init(true, new ParametersWithRandom(aPub)); byte[] result = sm2Engine.ProcessBlock(data, 0, data.Length); m_Logger.Debug($"[SM2Utils]Sm2Encrypt=>Utils.ByteArrayToHexString(result):{Utils.ByteArrayToHexString(result)}"); m_Logger.Debug($"[SM2Utils]Sm2Encrypt=>Utils.ByteArrayToHexString(result).Length:{Utils.ByteArrayToHexString(result).Length}"); return(Utils.ByteArrayToHexString(result).Substring(2)); }
private void DoEngineTestFp() { BigInteger SM2_ECC_P = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3", 16); BigInteger SM2_ECC_A = new BigInteger("787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", 16); BigInteger SM2_ECC_B = new BigInteger("63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", 16); BigInteger SM2_ECC_N = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", 16); BigInteger SM2_ECC_H = BigInteger.One; BigInteger SM2_ECC_GX = new BigInteger("421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", 16); BigInteger SM2_ECC_GY = new BigInteger("0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", 16); ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new TestRandomBigInteger("1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0", 16)); keyPairGenerator.Init(aKeyGenParams); AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair(); ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public; ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private; SM2Engine sm2Engine = new SM2Engine(); byte[] m = Strings.ToByteArray("encryption standard"); sm2Engine.Init(true, new ParametersWithRandom(aPub, new TestRandomBigInteger("4C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F", 16))); byte[] enc = sm2Engine.ProcessBlock(m, 0, m.Length); IsTrue("enc wrong", Arrays.AreEqual(Hex.Decode( "04245C26 FB68B1DD DDB12C4B 6BF9F2B6 D5FE60A3 83B0D18D 1C4144AB F17F6252" + "E776CB92 64C2A7E8 8E52B199 03FDC473 78F605E3 6811F5C0 7423A24B 84400F01" + "B8650053 A89B41C4 18B0C3AA D00D886C 00286467 9C3D7360 C30156FA B7C80A02" + "76712DA9 D8094A63 4B766D3A 285E0748 0653426D"), enc)); sm2Engine.Init(false, aPriv); byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); IsTrue("dec wrong", Arrays.AreEqual(m, dec)); enc[80] = (byte)(enc[80] + 1); try { sm2Engine.ProcessBlock(enc, 0, enc.Length); Fail("no exception"); } catch (InvalidCipherTextException e) { IsTrue("wrong exception", "invalid cipher text".Equals(e.Message)); } // long message sm2Engine = new SM2Engine(); m = new byte[4097]; for (int i = 0; i != m.Length; i++) { m[i] = (byte)i; } sm2Engine.Init(true, new ParametersWithRandom(aPub, new TestRandomBigInteger("4C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F", 16))); enc = sm2Engine.ProcessBlock(m, 0, m.Length); sm2Engine.Init(false, aPriv); dec = sm2Engine.ProcessBlock(enc, 0, enc.Length); IsTrue("dec wrong", Arrays.AreEqual(m, dec)); }