国密SM2公私钥HEX组装,密钥对生成


	private static X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");
	private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());

	
	private final static int SM2_KEY_LEN = 32;	
	public static ECPublicKey encodEcPublicKey(byte[] publickey)
			throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
		KeyFactory factory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
		if (publickey.length != SM2_KEY_LEN * 2)
			throw new RuntimeException("err key. ");
		BigInteger X = new BigInteger(1, Arrays.copyOfRange(publickey, 0, SM2_KEY_LEN));
		BigInteger Y = new BigInteger(1, Arrays.copyOfRange(publickey, SM2_KEY_LEN, SM2_KEY_LEN * 2));
		ECPoint point = CURVE.createPoint(X, Y);
		ECPublicKeySpec keySpec = new ECPublicKeySpec(point, ecDomainParameters);
		return (ECPublicKey) factory.generatePublic(keySpec);
	}

	public static ECPrivateKey encodEcPrivateKeyKey(byte[] privatekey)
			throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
		KeyFactory factory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
		if (privatekey.length != SM2_KEY_LEN)
			throw new RuntimeException("err key. ");
		ECPrivateKeySpec keySpec = new ECPrivateKeySpec(new BigInteger(1, privatekey), ecDomainParameters);
		return (ECPrivateKey) factory.generatePrivate(keySpec);
	}

	public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); 
		keyPairGenerator.initialize(ecDomainParameters, new SecureRandom());
		return keyPairGenerator.generateKeyPair();
	}
	

需要BC库,其它 自己研究了。

你可能感兴趣的:(国密)