SM2 encryption

	public void test2() {
		// The SM2 curve that has been defined in BC
		ECCurve localECCurve = GMNamedCurves.getByName("sm2p256v1").getCurve();
		// The public key der format has a prefix public key name, public key parameters, followed by XY, and xy must be preceded by 04, which means x and y, 03 means x is compressed, 02 means x is not compressed
		String s4 = "04F58EFDF08811BC76F52D08ABB6B62D2F9C3BFD5FACDAA7B6A7660F52236A5B8A2A3712FB6ACC90BE0519217BAED6EA47A1146610575924CCAB30B148FCEAE220";
		// Construct the public key point ECPoint
		X9ECPoint localX9ECPoint = new X9ECPoint(localECCurve, BaseUtils.hex2byte(s1));
		System.out.println(localX9ECPoint.getPoint());
		// Construct domainParams, which can be obtained from the defined SM2 curve
		ECDomainParameters domainParams = new ECDomainParameters(GMNamedCurves.getByName("sm2p256v1").getCurve(), GMNamedCurves
				.getByName("sm2p256v1").getG(), GMNamedCurves.getByName("sm2p256v1").getN());
		// There are public key points ECPoint and domainParams constructed as public key parameters
		ECPublicKeyParameters pk = new ECPublicKeyParameters(localX9ECPoint.getPoint(), domainParams);
		System.out.println(pk.getQ());

		// Use the lightweight API provided by BC for encryption
		SM2Engine sm2Engine = new SM2Engine();
		byte[] m = "encryption standard中午".getBytes();
		sm2Engine.init(true, new ParametersWithRandom(pk, new SecureRandom()));
		try {
			byte[] enc = sm2Engine.processBlock(m, 0, m.length);
			System.out.println("enc:" + BaseUtils.byte2hex(enc));
		} catch (InvalidCipherTextException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326223597&siteId=291194637