Java Code Examples for org.bouncycastle.crypto.AsymmetricCipherKeyPair#getPublic()

The following examples show how to use org.bouncycastle.crypto.AsymmetricCipherKeyPair#getPublic() . 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
Source File: LocalIdentity.java    From ts3j with 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 2
Source File: AccountServiceImpl.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 File: BouncyCastleV1CryptoProvider.java    From paseto with 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 4
Source File: BCECUtilTest.java    From gmhelper with 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 5
Source File: SM2UtilTest.java    From gmhelper with 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 6
Source File: SM2UtilTest.java    From gmhelper with 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 7
Source File: ECKeyPair.java    From bop-bitcoin-client with Apache License 2.0 5 votes vote down vote up
public static ECKeyPair createNew (boolean compressed)
{
	ECKeyPairGenerator generator = new ECKeyPairGenerator ();
	ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (domain, secureRandom);
	generator.init (keygenParams);
	AsymmetricCipherKeyPair keypair = generator.generateKeyPair ();
	ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate ();
	ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic ();
	ECKeyPair k = new ECKeyPair ();
	k.priv = privParams.getD ();
	k.compressed = compressed;
	k.pub = pubParams.getQ ().getEncoded (compressed);
	return k;
}
 
Example 8
Source File: ECKey.java    From nuls-v2 with 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 9
Source File: SM2.java    From julongchain with 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 10
Source File: Sm2KeyPairImpl.java    From littleca with 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 11
Source File: Cipher.java    From nuls with 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 12
Source File: SM2UtilTest.java    From gmhelper with 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 13
Source File: SM2UtilTest.java    From gmhelper with 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 14
Source File: SM2KeyExchangeUtilTest.java    From gmhelper with 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 15
Source File: SM2KeyExchangeUtilTest.java    From gmhelper with 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 16
Source File: SM2PreprocessSignerTest.java    From gmhelper with 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 File: ECKeyPair.java    From WalletCordova with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static ECKeyPair createNew (boolean compressed)
{
	ECKeyPairGenerator generator = new ECKeyPairGenerator ();
	ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (domain, secureRandom);
	generator.init (keygenParams);
	AsymmetricCipherKeyPair keypair = generator.generateKeyPair ();
	ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate ();
	ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic ();
	ECKeyPair k = new ECKeyPair ();
	k.priv = privParams.getD ();
	k.compressed = compressed;
	k.pub = pubParams.getQ ().getEncoded (compressed);
	return k;
}
 
Example 18
Source File: SM2UtilTest.java    From gmhelper with Apache License 2.0 4 votes vote down vote up
@Test
public void testKeyPairEncoding() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();

        byte[] priKeyPkcs8Der = BCECUtil.convertECPrivateKeyToPKCS8(priKey, pubKey);
        System.out.println("private key pkcs8 der length:" + priKeyPkcs8Der.length);
        System.out.println("private key pkcs8 der:" + ByteUtils.toHexString(priKeyPkcs8Der));
        FileUtil.writeFile("target/ec.pkcs8.pri.der", priKeyPkcs8Der);

        String priKeyPkcs8Pem = BCECUtil.convertECPrivateKeyPKCS8ToPEM(priKeyPkcs8Der);
        FileUtil.writeFile("target/ec.pkcs8.pri.pem", priKeyPkcs8Pem.getBytes("UTF-8"));
        byte[] priKeyFromPem = BCECUtil.convertECPrivateKeyPEMToPKCS8(priKeyPkcs8Pem);
        if (!Arrays.equals(priKeyFromPem, priKeyPkcs8Der)) {
            throw new Exception("priKeyFromPem != priKeyPkcs8Der");
        }

        BCECPrivateKey newPriKey = BCECUtil.convertPKCS8ToECPrivateKey(priKeyPkcs8Der);

        byte[] priKeyPkcs1Der = BCECUtil.convertECPrivateKeyToSEC1(priKey, pubKey);
        System.out.println("private key pkcs1 der length:" + priKeyPkcs1Der.length);
        System.out.println("private key pkcs1 der:" + ByteUtils.toHexString(priKeyPkcs1Der));
        FileUtil.writeFile("target/ec.pkcs1.pri", priKeyPkcs1Der);

        byte[] pubKeyX509Der = BCECUtil.convertECPublicKeyToX509(pubKey);
        System.out.println("public key der length:" + pubKeyX509Der.length);
        System.out.println("public key der:" + ByteUtils.toHexString(pubKeyX509Der));
        FileUtil.writeFile("target/ec.x509.pub.der", pubKeyX509Der);

        String pubKeyX509Pem = BCECUtil.convertECPublicKeyX509ToPEM(pubKeyX509Der);
        FileUtil.writeFile("target/ec.x509.pub.pem", pubKeyX509Pem.getBytes("UTF-8"));
        byte[] pubKeyFromPem = BCECUtil.convertECPublicKeyPEMToX509(pubKeyX509Pem);
        if (!Arrays.equals(pubKeyFromPem, pubKeyX509Der)) {
            throw new Exception("pubKeyFromPem != pubKeyX509Der");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 19
Source File: CryptographicUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static PublicKey getPublicKeyFromKeyPair(AsymmetricCipherKeyPair keyPair) throws Exception {
	Security.addProvider(new BouncyCastleProvider());

	RSAKeyParameters publicKey = (RSAKeyParameters)keyPair.getPublic();
	return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
}
 
Example 20
Source File: ECGEN.java    From warp10-platform with Apache License 2.0 2 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object top = stack.pop();

  if (!(top instanceof String)) {
    throw new WarpScriptException(getName() + " expects a curve name.");
  }

  String name = (String) top;

  ECKeyPairGenerator gen = new ECKeyPairGenerator();

  ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
  
  if (null == spec) {
    throw new WarpScriptException(getName() + " only supports the following curves: " + getCurves() + ".");
  }
  
  ECCurve curve = spec.getCurve();
  ECDomainParameters domainParams = new ECDomainParameters(curve, spec.getG(),spec.getN(), spec.getH(), spec.getSeed());    
  ECKeyGenerationParameters params = new ECKeyGenerationParameters(domainParams, CryptoHelper.getSecureRandom());
  
  gen.init(params);

  final AsymmetricCipherKeyPair keypair = gen.generateKeyPair();

  ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keypair.getPrivate();
  ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keypair.getPublic();
  
  Map<String,String> keyparams = new HashMap<String,String>();
  
  keyparams.put(Constants.KEY_CURVE, name);
  keyparams.put(Constants.KEY_D, privateKey.getD().toString());
  
  stack.push(keyparams);
  
  keyparams = new HashMap<String,String>();

  keyparams.put(Constants.KEY_CURVE, name);
  keyparams.put(Constants.KEY_Q, Hex.encodeHexString(publicKey.getQ().getEncoded()));

  stack.push(keyparams);

  return stack;
}