Java Code Examples for org.bouncycastle.crypto.AsymmetricCipherKeyPair

The following examples show how to use org.bouncycastle.crypto.AsymmetricCipherKeyPair. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private KeyPair createKeyPair() throws InvalidKeySpecException, NoSuchAlgorithmException {

        final RSAKeyPairGenerator gen = new RSAKeyPairGenerator();

        gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 80));
        final AsymmetricCipherKeyPair keypair = gen.generateKeyPair();

        final RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
        final RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();

        final PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(
                new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));

        final PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(
                new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                        privateKey.getExponent(), privateKey.getP(), privateKey.getQ(),
                        privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv()));

        return new KeyPair(pubKey, privKey);
    }
 
Example 2
@Override
public Account genAccount(Algo algo, String password) {
    byte[] address;
    byte[] publicKey;
    byte[] privateKey;
    ECKey ecKey;
    AsymmetricCipherKeyPair keyPair;
    if (algo.isSM()) {
        keyPair = SM2Util.generateKeyPair();
        ECPrivateKeyParameters ecPriv = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters ecPub = (ECPublicKeyParameters) keyPair.getPublic();
        BigInteger privateKeyBI = ecPriv.getD();

        publicKey = ecPub.getQ().getEncoded(false);
        privateKey = Account.encodePrivateKey(ByteUtil.biConvert32Bytes(privateKeyBI), algo, password);
        address = HashUtil.sha3omit12(publicKey);
        return new SMAccount(ByteUtil.toHex(address), ByteUtil.toHex(publicKey), ByteUtil.toHex(privateKey), Version.V4, algo, keyPair);
    } else {
        ecKey = new ECKey(new SecureRandom());
        address = ecKey.getAddress();
        publicKey = ecKey.getPubKey();
        privateKey = Account.encodePrivateKey(ecKey.getPrivKeyBytes(), algo, password);
        return new ECAccount(ByteUtil.toHex(address), ByteUtil.toHex(publicKey), ByteUtil.toHex(privateKey), Version.V4, algo, ecKey);
    }
}
 
Example 3
Source Project: gmhelper   Source File: BCECUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testECPrivateKeyPKCS8() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic();
        byte[] pkcs8Bytes = BCECUtil.convertECPrivateKeyToPKCS8(priKeyParams, pubKeyParams);
        BCECPrivateKey priKey = BCECUtil.convertPKCS8ToECPrivateKey(pkcs8Bytes);

        byte[] sign = SM2Util.sign(priKey, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA);
        System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign));
        boolean flag = SM2Util.verify(pubKeyParams, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA, sign);
        if (!flag) {
            Assert.fail("[withId] verify failed");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}
 
Example 4
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSM2KeyGen2() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        System.out.println("Pri Hex:"
            + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase());
        System.out.println("Pub Point Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase());
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 5
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeSM2CipherToDER() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        byte[] encryptedData = SM2Util.encrypt(pubKey, SRC_DATA);

        byte[] derCipher = SM2Util.encodeSM2CipherToDER(encryptedData);
        FileUtil.writeFile("target/derCipher.dat", derCipher);

        byte[] decryptedData = SM2Util.decrypt(priKey, SM2Util.decodeDERSM2Cipher(derCipher));
        if (!Arrays.equals(decryptedData, SRC_DATA)) {
            Assert.fail();
        }

        Assert.assertTrue(true);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 6
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeSM2CipherToDER_C1C2C3() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        byte[] encryptedData = SM2Util.encrypt(Mode.C1C2C3, pubKey, SRC_DATA);

        byte[] derCipher = SM2Util.encodeSM2CipherToDER(Mode.C1C2C3, encryptedData);
        FileUtil.writeFile("target/derCipher_c1c2c3.dat", derCipher);

        byte[] decryptedData = SM2Util.decrypt(Mode.C1C2C3, priKey, SM2Util.decodeDERSM2Cipher(Mode.C1C2C3, derCipher));
        if (!Arrays.equals(decryptedData, SRC_DATA)) {
            Assert.fail();
        }

        Assert.assertTrue(true);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 7
/**
 * @description 创建私钥和公钥
 * 
 * @return 私钥
 */
public static byte[] generatorPrivateKey() {
	int length = 0;
	byte[] privateKey;
	do {
		ECKeyPairGenerator gen = new ECKeyPairGenerator();
		SecureRandom secureRandom = new SecureRandom();
		X9ECParameters secnamecurves = SECNamedCurves.getByName("secp256k1");
		ECDomainParameters ecParams = new ECDomainParameters(secnamecurves.getCurve(), secnamecurves.getG(),
				secnamecurves.getN(), secnamecurves.getH());
		ECKeyGenerationParameters keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);
		gen.init(keyGenParam);
		AsymmetricCipherKeyPair kp = gen.generateKeyPair();
		ECPrivateKeyParameters privatekey = (ECPrivateKeyParameters) kp.getPrivate();
		privateKey = privatekey.getD().toByteArray();
		length = privatekey.getD().toByteArray().length;
	} while (length != 32);
	return privateKey;
}
 
Example 8
Source Project: paseto   Source File: BouncyCastleV1CryptoProvider.java    License: MIT License 6 votes vote down vote up
@Override
public KeyPair rsaGenerate() {
	RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator();
	keyGen.init(new RSAKeyGenerationParameters(E, new SecureRandom(), RSA_KEY_SIZE,
			PrimeCertaintyCalculator.getDefaultCertainty(RSA_KEY_SIZE)));
	AsymmetricCipherKeyPair pair = keyGen.generateKeyPair();

	RSAKeyParameters pub = (RSAKeyParameters) pair.getPublic();
	RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate();

	// As in BCRSAPrivateKey / BCRSAPublicKey
	AlgorithmIdentifier algo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);
	byte[] publicKey = KeyUtil.getEncodedSubjectPublicKeyInfo(algo, new RSAPublicKey(pub.getModulus(),
			pub.getExponent()));
	byte[] privateKey = KeyUtil.getEncodedPrivateKeyInfo(algo, new RSAPrivateKey(priv.getModulus(),
			priv.getPublicExponent(), priv.getExponent(), priv.getP(), priv.getQ(), priv.getDP(), priv.getDQ(),
			priv.getQInv()));

	return new KeyPair(privateKey, publicKey);
}
 
Example 9
Source Project: ts3j   Source File: LocalIdentity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a new identity with a given security level target.
 * @param securityLevel security level to generate for (may take time)
 * @return local identity with given security level
 * @throws GeneralSecurityException
 */
public static LocalIdentity generateNew(int securityLevel) throws GeneralSecurityException {
    ECNamedCurveParameterSpec ecp = ECNamedCurveTable.getParameterSpec("prime256v1");
    ECDomainParameters domainParams =
            new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed());
    ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());

    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keyGenParams);

    AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
    ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
    ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();

    LocalIdentity localIdentity = load(publicKey.getQ().normalize(), privateKey.getD());
    localIdentity.improveSecurity(securityLevel);

    return localIdentity;
}
 
Example 10
Source Project: jna-gmp   Source File: NativeRSAVectors.java    License: Apache License 2.0 6 votes vote down vote up
private static void generateTestVector(int rsaKeyBits, int suffix) throws Exception {
  AsymmetricCipherKeyPair pair = generateKeyPair(rsaKeyBits);
  RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate();

  byte[] message = new byte[rsaKeyBits / 8];
  SECURE_RANDOM.nextBytes(message);
  // Clear the top bit to ensure it fits.
  message[0] &= 0x7F;

  RSAEngine encoder = new RSAEngine();
  encoder.init(true, pair.getPrivate());
  byte[] signed = encoder.processBlock(message, 0, message.length);

  RSAEngine decoder = new RSAEngine();
  decoder.init(false, pair.getPublic());
  byte[] decoded = decoder.processBlock(signed, 0, message.length);

  Assert.assertArrayEquals(message, decoded);

  System.out.println("public static final TestVector VECTOR" + suffix + " = ");
  new TestVector(new BigInteger(1, message), new BigInteger(1, signed),
      (RSAPrivateCrtKeyParameters) pair.getPrivate()).printJavaConstructorFor();
  System.out.println();
}
 
Example 11
public static AsymmetricCipherKeyPair generateRsaKeyPair(int keyStrength) throws Exception {
	Security.addProvider(new BouncyCastleProvider());

	try {
		RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
		generator.init(new RSAKeyGenerationParameters(RSAKeyGenParameterSpec.F4, SecureRandom.getInstance("SHA1PRNG"), keyStrength, 80));
		AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
		return keyPair;
	} catch (Exception e) {
		throw new Exception("Cannot create RSA keypair", e);
	}
}
 
Example 12
public static PrivateKey getPrivateKeyFromKeyPair(AsymmetricCipherKeyPair keyPair) throws Exception {
	Security.addProvider(new BouncyCastleProvider());

	RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters)keyPair.getPrivate();
	RSAKeyParameters publicKey = (RSAKeyParameters)keyPair.getPublic();
	return KeyFactory.getInstance("RSA").generatePrivate(
			new RSAPrivateCrtKeySpec(privateKey.getModulus(), publicKey.getExponent(), privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(), privateKey.getDQ(),
					privateKey.getQInv()));
}
 
Example 13
Source Project: javasdk   Source File: SM2Util.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * create a random key pair of sm.
 *
 * @return String array of publicKey and privateKey
 */
public static AsymmetricCipherKeyPair generateKeyPair() {
    SecureRandom random = new SecureRandom();
    ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS, random);
    ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
    keyGen.init(keyGenerationParams);
    return keyGen.generateKeyPair();
}
 
Example 14
Source Project: javasdk   Source File: Account.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * get account from account json.
 *
 * @param accountJson account json
 * @param password    password
 * @return {@link Account}
 */
public static Account fromAccountJson(String accountJson, String password) {
    accountJson = parseAccountJson(accountJson, password);
    JsonObject jsonObject = new JsonParser().parse(accountJson).getAsJsonObject();
    String addressHex = jsonObject.get("address").getAsString();
    String publicKeyHex = jsonObject.get("publicKey").getAsString();
    String privateKeyHex = jsonObject.get("privateKey").getAsString();
    Version version = Version.getVersion(jsonObject.get("version").getAsString());
    Algo algo = Algo.getAlog(jsonObject.get("algo").getAsString());
    byte[] privateKey = decodePrivateKey(ByteUtil.fromHex(privateKeyHex), algo, password);
    if (algo.isSM()) {
        ECPoint ecPoint = SM2Util.CURVE.decodePoint(ByteUtil.fromHex(publicKeyHex));
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(ecPoint, SM2Util.DOMAIN_PARAMS);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privateKey), SM2Util.DOMAIN_PARAMS);
        AsymmetricCipherKeyPair asymmetricCipherKeyPair = new AsymmetricCipherKeyPair(publicKeyParameters, privateKeyParameters);
        if (!addressHex.equals(ByteUtil.toHex(HashUtil.sha3omit12(publicKeyParameters.getQ().getEncoded(false))))) {
            throw new AccountException("account address is not matching with private key");
        }
        return new SMAccount(addressHex, publicKeyHex, privateKeyHex, version, algo, asymmetricCipherKeyPair);
    } else {
        ECKey ecKey = ECKey.fromPrivate(privateKey);
        if (!addressHex.equals(ByteUtil.toHex(ecKey.getAddress()))) {
            throw new AccountException("account address is not matching with private key");
        }
        return new ECAccount(addressHex, publicKeyHex, privateKeyHex, version, algo, ecKey);
    }
}
 
Example 15
Source Project: gmhelper   Source File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成ECC密钥对
 *
 * @return ECC密钥对
 */
public static AsymmetricCipherKeyPair generateKeyPairParameter(
        ECDomainParameters domainParameters, SecureRandom random) {
    ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters,
            random);
    ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
    keyGen.init(keyGenerationParams);
    return keyGen.generateKeyPair();
}
 
Example 16
Source Project: gmhelper   Source File: SM2PreprocessSignerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws CryptoException {
    AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
    ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
    ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

    SM2PreprocessSigner signer = new SM2PreprocessSigner();
    CipherParameters pwr = new ParametersWithRandom(priKey, new SecureRandom());
    signer.init(true, pwr);
    byte[] eHash1 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length);
    byte[] sign1 = signer.generateSignature(eHash1);

    signer = new SM2PreprocessSigner();
    signer.init(false, pubKey);
    byte[] eHash2 = signer.preprocess(SRC_DATA, 0, SRC_DATA.length);
    if (!Arrays.equals(eHash1, eHash2)) {
        Assert.fail();
    }
    if (!signer.verifySignature(eHash1, sign1)) {
        Assert.fail();
    }
}
 
Example 17
Source Project: gmhelper   Source File: SM2KeyExchangeUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCaculateKey() {
    try {
        AsymmetricCipherKeyPair initiatorStaticKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters initiatorStaticPriv = (ECPrivateKeyParameters) initiatorStaticKp.getPrivate();
        ECPublicKeyParameters initiatorStaticPub = (ECPublicKeyParameters) initiatorStaticKp.getPublic();
        AsymmetricCipherKeyPair initiatorEphemeralKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters initiatorEphemeralPriv = (ECPrivateKeyParameters) initiatorEphemeralKp.getPrivate();
        ECPublicKeyParameters initiatorSEphemeralPub = (ECPublicKeyParameters) initiatorEphemeralKp.getPublic();
        AsymmetricCipherKeyPair responderStaticKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters responderStaticPriv = (ECPrivateKeyParameters) responderStaticKp.getPrivate();
        ECPublicKeyParameters responderStaticPub = (ECPublicKeyParameters) responderStaticKp.getPublic();
        AsymmetricCipherKeyPair responderEphemeralKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters responderEphemeralPriv = (ECPrivateKeyParameters) responderEphemeralKp.getPrivate();
        ECPublicKeyParameters responderSEphemeralPub = (ECPublicKeyParameters) responderEphemeralKp.getPublic();

        //实际应用中应该是通过网络交换临时公钥
        byte[] k1 = SM2KeyExchangeUtil.calculateKey(true, KEY_BITS,
            initiatorStaticPriv, initiatorEphemeralPriv, INITIATOR_ID,
            responderStaticPub, responderSEphemeralPub, RESPONDER_ID);
        byte[] k2 = SM2KeyExchangeUtil.calculateKey(false, KEY_BITS,
            responderStaticPriv, responderEphemeralPriv, RESPONDER_ID,
            initiatorStaticPub, initiatorSEphemeralPub, INITIATOR_ID);

        if (!Arrays.equals(k1, k2)) {
            Assert.fail();
        }
    } catch (Exception ex) {
        Assert.fail();
    }
}
 
Example 18
Source Project: gmhelper   Source File: SM2KeyExchangeUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCalculateKeyWithConfirmation() {
    try {
        AsymmetricCipherKeyPair initiatorStaticKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters initiatorStaticPriv = (ECPrivateKeyParameters) initiatorStaticKp.getPrivate();
        ECPublicKeyParameters initiatorStaticPub = (ECPublicKeyParameters) initiatorStaticKp.getPublic();
        AsymmetricCipherKeyPair initiatorEphemeralKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters initiatorEphemeralPriv = (ECPrivateKeyParameters) initiatorEphemeralKp.getPrivate();
        ECPublicKeyParameters initiatorSEphemeralPub = (ECPublicKeyParameters) initiatorEphemeralKp.getPublic();
        AsymmetricCipherKeyPair responderStaticKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters responderStaticPriv = (ECPrivateKeyParameters) responderStaticKp.getPrivate();
        ECPublicKeyParameters responderStaticPub = (ECPublicKeyParameters) responderStaticKp.getPublic();
        AsymmetricCipherKeyPair responderEphemeralKp = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters responderEphemeralPriv = (ECPrivateKeyParameters) responderEphemeralKp.getPrivate();
        ECPublicKeyParameters responderSEphemeralPub = (ECPublicKeyParameters) responderEphemeralKp.getPublic();

        //第一步应该是交换临时公钥等信息

        //第二步响应方生成密钥和验证信息
        SM2KeyExchangeUtil.ExchangeResult responderResult = SM2KeyExchangeUtil.calculateKeyWithConfirmation(
            false, KEY_BITS, null,
            responderStaticPriv, responderEphemeralPriv, RESPONDER_ID,
            initiatorStaticPub, initiatorSEphemeralPub, INITIATOR_ID);

        //第三步发起方生成密钥和验证消息,并验证响应方的验证消息
        SM2KeyExchangeUtil.ExchangeResult initiatorResult = SM2KeyExchangeUtil.calculateKeyWithConfirmation(
            true, KEY_BITS, responderResult.getS1(),
            initiatorStaticPriv, initiatorEphemeralPriv, INITIATOR_ID,
            responderStaticPub, responderSEphemeralPub, RESPONDER_ID);

        //第四步响应方验证发起方的验证消息
        if (!SM2KeyExchangeUtil.responderConfirm(responderResult.getS2(), initiatorResult.getS2())) {
            Assert.fail();
        }
    } catch (Exception ex) {
        Assert.fail();
    }
}
 
Example 19
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSignAndVerify() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        System.out.println("Pri Hex:"
            + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase());
        System.out.println("Pub Point Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase());

        byte[] sign = SM2Util.sign(priKey, WITH_ID, SRC_DATA);
        System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign));
        byte[] rawSign = SM2Util.decodeDERSM2Sign(sign);
        sign = SM2Util.encodeSM2SignToDER(rawSign);
        System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign));
        boolean flag = SM2Util.verify(pubKey, WITH_ID, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }

        sign = SM2Util.sign(priKey, SRC_DATA);
        System.out.println("SM2 sign without withId result:\n" + ByteUtils.toHexString(sign));
        flag = SM2Util.verify(pubKey, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 20
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptAndDecrypt() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        System.out.println("Pri Hex:"
            + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase());
        System.out.println("Pub Point Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase());

        byte[] encryptedData = SM2Util.encrypt(pubKey, SRC_DATA_24B);
        System.out.println("SM2 encrypt result:\n" + ByteUtils.toHexString(encryptedData));
        byte[] decryptedData = SM2Util.decrypt(priKey, encryptedData);
        System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(decryptedData));
        if (!Arrays.equals(decryptedData, SRC_DATA_24B)) {
            Assert.fail();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 21
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptAndDecrypt_C1C2C3() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        System.out.println("Pri Hex:"
            + ByteUtils.toHexString(priKey.getD().toByteArray()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineXCoord().getEncoded()).toUpperCase());
        System.out.println("Pub X Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getAffineYCoord().getEncoded()).toUpperCase());
        System.out.println("Pub Point Hex:"
            + ByteUtils.toHexString(pubKey.getQ().getEncoded(false)).toUpperCase());

        byte[] encryptedData = SM2Util.encrypt(Mode.C1C3C2, pubKey, SRC_DATA_48B);
        System.out.println("SM2 encrypt result:\n" + ByteUtils.toHexString(encryptedData));
        byte[] decryptedData = SM2Util.decrypt(Mode.C1C3C2, priKey, encryptedData);
        System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(decryptedData));
        if (!Arrays.equals(decryptedData, SRC_DATA_48B)) {
            Assert.fail();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 22
Source Project: littleca   Source File: Sm2KeyPairImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Sm2KeyPairImpl(boolean selfgen) {
	SecureRandom random = new SecureRandom();
	ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS, random);
	ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
	keyGen.init(keyGenerationParams);
	AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair();
	ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
	ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();
	ECDomainParameters domainParams = priKey.getParameters();
	ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(), domainParams.getN(),
			domainParams.getH());
	BCECPublicKey bcecPublicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec, BouncyCastleProvider.CONFIGURATION);
	publicKey = new Sm2PublicKeyImpl(bcecPublicKey);
	privateKey = new Sm2PrivateKeyImpl(new BCECPrivateKey(ALGO_NAME_EC, priKey, bcecPublicKey, spec, BouncyCastleProvider.CONFIGURATION));
}
 
Example 23
Source Project: littleca   Source File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成ECC密钥对
 *
 * @return ECC密钥对
 */
public static AsymmetricCipherKeyPair generateKeyPair(ECDomainParameters domainParameters,
                                                      SecureRandom random) {
    ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters,
        random);
    ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
    keyGen.init(keyGenerationParams);
    return keyGen.generateKeyPair();
}
 
Example 24
Source Project: julongchain   Source File: SM2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * sm2密钥对生成
 *
 * @return
 */
public SM2KeyPair generateKeyPair() {
    ECKeyGenerationParameters ecKeyGenerationParameters = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom());
    ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
    keyPairGenerator.init(ecKeyGenerationParameters);
    AsymmetricCipherKeyPair kp = keyPairGenerator.generateKeyPair();
    ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) kp.getPrivate();
    ECPublicKeyParameters ecpub = (ECPublicKeyParameters) kp.getPublic();
    BigInteger privateKey = ecpriv.getD();
    ECPoint publicKey = ecpub.getQ();
    return new SM2KeyPair(publicKey.getEncoded(false), privateKey.toByteArray());
}
 
Example 25
Source Project: nuls-v2   Source File: ECKey.java    License: MIT License 5 votes vote down vote up
/**
 * Generates an entirely new keypair with the given {@link SecureRandom} object. Point compression is used so the
 * resulting public key will be 33 bytes (32 for the co-ordinate and 1 byte to represent the y bit).
 */
public ECKey(SecureRandom secureRandom) {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
    priv = privParams.getD();
    pub = new LazyECPoint(CURVE.getCurve(), pubParams.getQ().getEncoded(true));
    creationTimeSeconds = System.currentTimeMillis();
}
 
Example 26
Source Project: nuls   Source File: Cipher.java    License: MIT License 5 votes vote down vote up
public ECPoint initEnc(SM2 sm2, ECPoint userKey) {
    AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
    ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
    ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
    BigInteger k = ecpriv.getD();
    ECPoint c1 = ecpub.getQ();
    this.p2 = userKey.multiply(k);
    reset();
    return c1;
}
 
Example 27
Source Project: fabric-api-archive   Source File: BouncyCastleCrypto.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] createNewPrivateKey() {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    return privParams.getD().toByteArray();
}
 
Example 28
Source Project: fabric-api   Source File: BouncyCastleCrypto.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] createNewPrivateKey() {
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(domain, secureRandom);
    generator.init(keygenParams);
    AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
    ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
    return privParams.getD().toByteArray();
}
 
Example 29
@BeforeClass
public static void setUpClass() throws CoseException {

    X9ECParameters p = NISTNamedCurves.getByName("P-256");
    
    ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());
    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, null);
    pGen.init(genParam);
    
    AsymmetricCipherKeyPair p1 = pGen.generateKeyPair();
    
    keyPublic = (ECPublicKeyParameters) p1.getPublic();
    keyPrivate = (ECPrivateKeyParameters) p1.getPrivate();
    
byte[] rgbX = keyPublic.getQ().normalize().getXCoord().getEncoded();
byte[] rgbY = keyPublic.getQ().normalize().getYCoord().getEncoded();
boolean signY = true;
byte[] rgbD = keyPrivate.getD().toByteArray();

CBORObject key = CBORObject.NewMap();
    key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2);
    key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256);
    key.Add(KeyKeys.EC2_X.AsCBOR(), rgbX);
    key.Add(KeyKeys.EC2_Y.AsCBOR(), rgbY);
    cnKeyPublic = new OneKey(key);
    
    key = CBORObject.NewMap();
    key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2);
    key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256);
    key.Add(KeyKeys.EC2_X.AsCBOR(), rgbX);
    key.Add(KeyKeys.EC2_Y.AsCBOR(), rgbY);
    cnKeyPublicCompressed = new OneKey(key);

    key = CBORObject.NewMap();
    key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2);
    key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256);
    key.Add(KeyKeys.EC2_D.AsCBOR(), rgbD);
    cnKeyPrivate = new OneKey(key);
}
 
Example 30
Source Project: jiguang-java-client-common   Source File: BCECUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 生成ECC密钥对
 *
 * @return ECC密钥对
 */
public static AsymmetricCipherKeyPair generateKeyPairParameter(ECDomainParameters domainParameters,
    SecureRandom random) {
    ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters,
        random);
    ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
    keyGen.init(keyGenerationParams);
    return keyGen.generateKeyPair();
}