Java通用C# SM2加密解密

        起因是对接一个接口 他们只能提供java deom c#的没有,  百度了一天不能适配, 只能看java 还原的C#。

 代码

public class SM2CryptoUtil
    {

        public SM2CryptoUtil(string pubkey, string privkey, Mode mode = Mode.C1C2C3, bool isPkcs8 = false)
        {
            if (pubkey != null)
                this.pubkey = pubkey;
            if (privkey != null)
                this.privkey = privkey;
            this.mode = mode;
        }
        string pubkey;
       string privkey;
        Mode mode;

        ICipherParameters _privateKeyParameters;
        ICipherParameters PrivateKeyParameters
        {
            get
            {
                try
                {
                    var r = _privateKeyParameters;
                    if (r == null) r = _privateKeyParameters =
                            new ECPrivateKeyParameters(new BigInteger(privkey, 16),
                            new ECDomainParameters(GMNamedCurves.GetByName("SM2P256V1")));
                    return r;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }

        ICipherParameters _publicKeyParameters;
        ICipherParameters PublicKeyParameters
        {
            get
            {
                try
                {
                    var r = _publicKeyParameters;
                    if (r == null)
                    {
                        //截取64字节有效的SM2公钥(如果公钥首个字节为0x04)
                        if (pubkey.Length > 128)
                        {
                            pubkey = pubkey.Substring(pubkey.Length - 128);
                        }
                        //将公钥拆分为x,y分量(各32字节)
                        String stringX = pubkey.Substring(0, 64);
                        String stringY = pubkey.Substring(stringX.Length);
                        //将公钥x、y分量转换为BigInteger类型
                        BigInteger x = new BigInteger(stringX, 16);
                        BigInteger y = new BigInteger(stringY, 16);
                        //通过公钥x、y分量创建椭圆曲线公钥规范
                        var x9ec = GMNamedCurves.GetByName("SM2P256V1");
                        r = _publicKeyParameters = new ECPublicKeyParameters(x9ec.Curve.CreatePoint(x,y),
                            new ECDomainParameters(x9ec));
                    }
                    return r;
                }
                catch (Exception ex)
                {
                    return null;
                            ;
                }
            }
        }

        public byte[] Decrypt(byte[] data)
        {
            try
            {
                if (mode == Mode.C1C3C2)
                    data = C132ToC123(data);
                var sm2 = new SM2Engine();
                sm2.Init(false, this.PrivateKeyParameters);
                return sm2.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception ex) 
            {
                return null;
            }
        }
        public byte[] Encrypt(byte[] data)
        {
            try
            {
                //  var sm2 = new SM2Engine(new SM3Digest());
                var sm2 = new SM2Engine();
                sm2.Init(true, new ParametersWithRandom(this.PublicKeyParameters));
                data = sm2.ProcessBlock(data, 0, data.Length);
                if (mode == Mode.C1C3C2) 
                    data = C123ToC132(data);
                return data;
            }
            catch (Exception ex) 
            {
                return null;
            }
        }

        static byte[] C123ToC132(byte[] c1c2c3)
        {
            var gn = GMNamedCurves.GetByName("SM2P256V1");
            int c1Len = (gn.Curve.FieldSize + 7) / 8 * 2 + 1;
            int c3Len = 32;
            byte[] result = new byte[c1c2c3.Length];
            Array.Copy(c1c2c3, 0, result, 0, c1Len); //c1
            Array.Copy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
            Array.Copy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
            return result;

        }
        static byte[] C132ToC123(byte[] c1c3c2)
        {
            var gn = GMNamedCurves.GetByName("SM2P256V1");
            int c1Len = (gn.Curve.FieldSize + 7) / 8 * 2 + 1;
            int c3Len = 32;
            byte[] result = new byte[c1c3c2.Length];
            Array.Copy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
            Array.Copy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
            Array.Copy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
            return result;

        }
        public enum Mode
        {
            C1C2C3, C1C3C2
        }
    }

调用方式

//实例化

string pukey="";

string PRKEY="";

var handle = new SM2CryptoUtil(pukey, PRKEY, SM2CryptoUtil.Mode.C1C3C2);
//加密
string str="";
var Encryptdata = handle.Encrypt(System.Text.Encoding.UTF8.GetBytes(str));
string datac = Hex.ToHexString(Encryptdata);
//解密
string str="";
var original = handle.Decrypt(Hex.Decode(str));
string data = System.Text.Encoding.Default.GetString(original);

 如果不能用 请留言
苦逼呀!!!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
Java可以使用Bouncy Castle库来实现SM2加密解密。下面是一个示例代码: ```java import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.engines.SM2Engine; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import java.security.Security; import java.security.SecureRandom; public class SM2Example { public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); // 生成密钥对 ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(SM2Util.DOMAIN_PARAMS, new SecureRandom()); keyPairGenerator.init(keyGenerationParameters); AsymmetricCipherKeyPair keyPair = keyPairGenerator.generateKeyPair(); // 获取公钥和私钥 ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); // 加密 String plaintext = "Hello, SM2!"; byte[] plaintextBytes = plaintext.getBytes("UTF-8"); CipherParameters encryptParams = new ParametersWithRandom(publicKey, new SecureRandom()); SM2Engine encryptEngine = new SM2Engine(); encryptEngine.init(true, encryptParams); byte[] ciphertextBytes = encryptEngine.processBlock(plaintextBytes, 0, plaintextBytes.length); // 解密 CipherParameters decryptParams = new ParametersWithRandom(privateKey, new SecureRandom()); SM2Engine decryptEngine = new SM2Engine(); decryptEngine.init(false, decryptParams); byte[] decryptedBytes = decryptEngine.processBlock(ciphertextBytes, 0, ciphertextBytes.length); String decryptedText = new String(decryptedBytes, "UTF-8"); System.out.println("Plaintext: " + plaintext); System.out.println("Ciphertext: " + Hex.toHexString(ciphertextBytes)); System.out.println("Decrypted text: " + decryptedText); } } ``` 这段代码使用Bouncy Castle库生成SM2密钥对,然后使用公钥加密明文,私钥解密密文。注意,需要先导入Bouncy Castle库,并且确保密钥对的生成参数`SM2Util.DOMAIN_PARAMS`正确设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值