org.bouncycastle.jce.spec.ECParameterSpec Java Examples

The following examples show how to use org.bouncycastle.jce.spec.ECParameterSpec. 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: EOSFormatter.java    From eosio-java with MIT License 6 votes vote down vote up
/**
 * Decompresses a public key based on the algorithm used to generate it.
 *
 * @param compressedPublicKey Compressed public key as byte[]
 * @param algorithmEmployed Algorithm used during key creation
 * @return Decompressed public key as byte[]
 * @throws EOSFormatterError when public key decompression fails.
 */
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
        AlgorithmEmployed algorithmEmployed)
        throws EOSFormatterError {
    try {
        ECParameterSpec parameterSpec = ECNamedCurveTable
                .getParameterSpec(algorithmEmployed.getString());
        ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
        byte[] x = ecPoint.getXCoord().getEncoded();
        byte[] y = ecPoint.getYCoord().getEncoded();
        if (y.length > STANDARD_KEY_LENGTH) {
            y = Arrays.copyOfRange(y, 1, y.length);
        }
        return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
    }
}
 
Example #2
Source File: ECDHExportTest.java    From Encryptor4j with MIT License 6 votes vote down vote up
@Test
public void testExportImport() throws GeneralSecurityException {

	// Create a curve25519 parameter spec
	X9ECParameters params = CustomNamedCurves.getByName("curve25519");
	ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed());

	// Create public key
	KeyAgreementPeer peer = new ECDHPeer(ecParameterSpec, null, "BC");
	ECPublicKey ecPublicKey = (ECPublicKey) peer.getPublicKey();

	// Export public key
	byte[] encoded = ecPublicKey.getQ().getEncoded(true);

	System.out.println(Arrays.toString(encoded));
	System.out.println("Encoded length: " + encoded.length);

	// Import public key
	ECPublicKey importedECPublicKey = loadPublicKey(encoded);

	Assert.assertArrayEquals(ecPublicKey.getEncoded(), importedECPublicKey.getEncoded());
}
 
Example #3
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
private void verifySignResp(byte[] data, APDUResponse response) throws Exception {
  Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
  assertEquals(0x9000, response.getSw());
  byte[] sig = response.getData();
  byte[] keyData = extractPublicKeyFromSignature(sig);
  sig = extractSignature(sig);

  ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
  ECPublicKeySpec cardKeySpec = new ECPublicKeySpec(ecSpec.getCurve().decodePoint(keyData), ecSpec);
  ECPublicKey cardKey = (ECPublicKey) KeyFactory.getInstance("ECDSA", "BC").generatePublic(cardKeySpec);

  signature.initVerify(cardKey);
  assertEquals((SecureChannel.SC_KEY_LENGTH * 2 / 8) + 1, keyData.length);
  signature.update(data);
  assertTrue(signature.verify(sig));
  assertFalse(isMalleable(sig));
}
 
Example #4
Source File: Keys.java    From blockchain with Apache License 2.0 6 votes vote down vote up
/**
 * Create a keypair using SECP-256k1 curve.
 *
 * <p>Private keypairs are encoded using PKCS8
 *
 * <p>Private keys are encoded using X.509
 */
static KeyPair createSecp256k1KeyPair() throws NoSuchProviderException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException {

    // 注册 BC Provider
    Security.addProvider(new BouncyCastleProvider());
    // 创建椭圆曲线算法的密钥对生成器
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            CryptoConstants.KEY_GEN_ALGORITHM,
            BouncyCastleProvider
            .PROVIDER_NAME);
    // 椭圆曲线(EC)域参数设定
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CryptoConstants.EC_PARAM_SPEC);
    keyPairGenerator.initialize(ecSpec, new SecureRandom());
    return keyPairGenerator.generateKeyPair();
}
 
Example #5
Source File: BouncyCryptography.java    From Jabit with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSignatureValid(byte[] data, byte[] signature, Pubkey pubkey) {
    try {
        ECParameterSpec spec = new ECParameterSpec(
            EC_CURVE_PARAMETERS.getCurve(),
            EC_CURVE_PARAMETERS.getG(),
            EC_CURVE_PARAMETERS.getN(),
            EC_CURVE_PARAMETERS.getH(),
            EC_CURVE_PARAMETERS.getSeed()
        );

        ECPoint Q = keyToPoint(pubkey.getSigningKey());
        KeySpec keySpec = new ECPublicKeySpec(Q, spec);
        PublicKey publicKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider).generatePublic(keySpec);

        Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider);
        sig.initVerify(publicKey);
        sig.update(data);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        throw new ApplicationException(e);
    }
}
 
Example #6
Source File: BouncyCryptography.java    From Jabit with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getSignature(byte[] data, PrivateKey privateKey) {
    try {
        ECParameterSpec spec = new ECParameterSpec(
            EC_CURVE_PARAMETERS.getCurve(),
            EC_CURVE_PARAMETERS.getG(),
            EC_CURVE_PARAMETERS.getN(),
            EC_CURVE_PARAMETERS.getH(),
            EC_CURVE_PARAMETERS.getSeed()
        );

        BigInteger d = keyToBigInt(privateKey.getPrivateSigningKey());
        KeySpec keySpec = new ECPrivateKeySpec(d, spec);
        java.security.PrivateKey privKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider)
            .generatePrivate(keySpec);

        Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider);
        sig.initSign(privKey);
        sig.update(data);
        return sig.sign();
    } catch (GeneralSecurityException e) {
        throw new ApplicationException(e);
    }
}
 
Example #7
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {

    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();

}
 
Example #8
Source File: DynamoDbSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    
    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();
    
    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();
    
    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();
    
}
 
Example #9
Source File: SHA256withECDSASignatureVerification.java    From oxAuth with MIT License 6 votes vote down vote up
@Override
 public PublicKey decodePublicKey(byte[] encodedPublicKey) throws SignatureException {
         X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
         ECPoint point = curve.getCurve().decodePoint(encodedPublicKey);

         try {
	return KeyFactory.getInstance("ECDSA").generatePublic(
	        new ECPublicKeySpec(point,
	                new ECParameterSpec(
	                        curve.getCurve(),
	                        curve.getG(),
	                        curve.getN(),
	                        curve.getH()
	                )
	        )
	);
} catch (GeneralSecurityException ex) {
	throw new SignatureException(ex);
}
 }
 
Example #10
Source File: DynamoDBEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private EncryptionMaterialsProvider getMaterialProviderwithECDSA()
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    Map<String, String> description = new HashMap<String, String>();
    description.put(DynamoDBEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
    return new SymmetricStaticProvider(null, keypair, description);
}
 
Example #11
Source File: DynamoDbEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private EncryptionMaterialsProvider getMaterialProviderwithECDSA() 
       throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
        g.initialize(ecSpec, Utils.getRng());
        KeyPair keypair = g.generateKeyPair();
        Map<String, String> description = new HashMap<>();
        description.put(DynamoDbEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
        return new SymmetricStaticProvider(null, keypair, description);
}
 
Example #12
Source File: KeyCodec.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static KeyPair generate() throws NoSuchAlgorithmException,
		InvalidAlgorithmParameterException {
	SecureRandom random = new SecureRandom();
	ECParameterSpec ecSpec = ECNamedCurveTable
			.getParameterSpec("secp256r1");
	KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA");
	g.initialize(ecSpec, random);
	return g.generateKeyPair();
}
 
Example #13
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
/**
 * 将ECC公钥对象转换为X509标准的字节流
 *
 * @param pubKey
 * @return
 */
public static byte[] convertECPublicKeyToX509(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
        domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
        BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example #14
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
    throws NoSuchProviderException, NoSuchAlgorithmException,
    InvalidAlgorithmParameterException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
        domainParameters.getN(), domainParameters.getH());
    kpg.initialize(parameterSpec, random);
    return kpg.generateKeyPair();
}
 
Example #15
Source File: DataStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetInvalidCurveName() {
    ChangeLogStore clogStore = new MockZMSFileChangeLogStore("/tmp/zts_server_unit_tests/zts_root",
            pkey, "0");
    DataStore store = new DataStore(clogStore, null);
    ECParameterSpec spec = Mockito.mock(ECParameterSpec.class);
    when(spec.getCurve()).thenReturn(null);
    when(spec.getG()).thenReturn(null);
    when(spec.getH()).thenReturn(new BigInteger("100"));
    when(spec.getN()).thenReturn(new BigInteger("100"));
    assertNull(store.getCurveName(spec, false));
}
 
Example #16
Source File: ECPRIVATE.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object top = stack.pop();
  
  if (!(top instanceof Map)) {
    throw new WarpScriptException(getName() + " expects a parameter map.");
  }
  
  Map<Object,Object> params = (Map<Object,Object>) top;
  
  String name = String.valueOf(params.get(Constants.KEY_CURVE));
  
  final ECNamedCurveParameterSpec curve = ECNamedCurveTable.getParameterSpec(name);
  
  if (null == curve) {
    throw new WarpScriptException(getName() + " curve name not in " + ECGEN.getCurves() + ".");
  }

  if (!(params.get(Constants.KEY_D) instanceof String)) {
    throw new WarpScriptException(getName() + " missing or non-String parameter '" + Constants.KEY_D + "'.");
  }

  final BigInteger d = new BigInteger((String) params.get(Constants.KEY_D));
  
  ECPrivateKey privateKey = new ECPrivateKey() {
    public String getFormat() { return "PKCS#8"; }
    public byte[] getEncoded() { return null; }
    public String getAlgorithm() { return "EC"; }
    public ECParameterSpec getParameters() { return curve; }
    public BigInteger getD() { return d; }
  };
    
  stack.push(privateKey);
  
  return stack;
}
 
Example #17
Source File: ECPUBLIC.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object top = stack.pop();
  
  if (!(top instanceof Map)) {
    throw new WarpScriptException(getName() + " expects a parameter map.");
  }
  
  Map<Object,Object> params = (Map<Object,Object>) top;
  
  String name = String.valueOf(params.get(Constants.KEY_CURVE));
  
  final ECNamedCurveParameterSpec curve = ECNamedCurveTable.getParameterSpec(name);

  if (null == curve) {
    throw new WarpScriptException(getName() + " curve name not in " + ECGEN.getCurves() + ".");
  }
  
  if (!(params.get(Constants.KEY_Q) instanceof String)) {
    throw new WarpScriptException(getName() + " missing or non-String parameter '" + Constants.KEY_Q + "'.");
  }
  
  final byte[] encoded = Hex.decode((String) params.get(Constants.KEY_Q));
  
  final ECPoint q = curve.getCurve().decodePoint(encoded);
      
  ECPublicKey publicKey = new ECPublicKey() {
    public String getFormat() { return "PKCS#8"; }
    public byte[] getEncoded() { return encoded; }
    public String getAlgorithm() { return "EC"; }
    public ECParameterSpec getParameters() { return curve; }
    public ECPoint getQ() { return q; }
  };
    
  stack.push(publicKey);
  
  return stack;
}
 
Example #18
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Load a public key from the private key.
 *
 * @param privateKey
 * @return
 */
public static ECPublicKey loadPublicKey(ECPrivateKey privateKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPoint Q = ecSpec.getG().multiply(privateKey.getD());
    byte[] publicDerBytes = Q.getEncoded(false);
    ECPoint point = ecSpec.getCurve().decodePoint(publicDerBytes);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

    return (ECPublicKey) keyFactory.generatePublic(pubSpec);
}
 
Example #19
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Load the public key from a byte array. 
 *
 * @param decodedPublicKey
 */
public static PublicKey loadPublicKey(byte[] decodedPublicKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);
}
 
Example #20
Source File: ECDHExportTest.java    From Encryptor4j with MIT License 5 votes vote down vote up
/**
 * Loads and returns the elliptic-curve public key from the data byte array.
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
public static ECPublicKey loadPublicKey(byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException
{
	X9ECParameters params = CustomNamedCurves.getByName("curve25519");
	ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed());

	ECPublicKeySpec publicKey = new ECPublicKeySpec(ecParameterSpec.getCurve().decodePoint(data), ecParameterSpec);
	KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
	return (ECPublicKey) kf.generatePublic(publicKey);
}
 
Example #21
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPrivateKey = Base64Encoder.decode(privateKey);
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER);

    return keyFactory.generatePrivate(privateKeySpec);
}
 
Example #22
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public static PublicKey loadPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPublicKey = Base64Encoder.decode(publicKey);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);

}
 
Example #23
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 5 votes vote down vote up
private KeyPairGenerator keypairGenerator() throws Exception {
  ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
  KeyPairGenerator g = KeyPairGenerator.getInstance("ECDH", "BC");
  g.initialize(ecSpec);

  return g;
}
 
Example #24
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeyPair(ECDomainParameters domainParameters, SecureRandom random)
        throws NoSuchProviderException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    ECParameterSpec parameterSpec = new ECParameterSpec(domainParameters.getCurve(), domainParameters.getG(),
            domainParameters.getN(), domainParameters.getH());
    kpg.initialize(parameterSpec, random);
    return kpg.generateKeyPair();
}
 
Example #25
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * 将ECC公钥对象转换为X509标准的字节流
 *
 * @param pubKey
 * @return
 */
public static byte[] convertECPublicKeyToX509(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
            domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
            BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example #26
Source File: SM2CertUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static BCECPublicKey getBCECPublicKey(X509Certificate sm2Cert) {
    ECPublicKey pubKey = (ECPublicKey) sm2Cert.getPublicKey();
    ECPoint q = pubKey.getQ();
    ECParameterSpec parameterSpec = new ECParameterSpec(SM2Util.CURVE, SM2Util.G_POINT,
        SM2Util.SM2_ECC_N, SM2Util.SM2_ECC_H);
    ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(q, parameterSpec);
    return new BCECPublicKey(pubKey.getAlgorithm(), pubKeySpec,
        BouncyCastleProvider.CONFIGURATION);
}
 
Example #27
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 #28
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static byte[] convertEcPubKeyToX509Der(ECPublicKeyParameters pubKey) {
    ECDomainParameters domainParams = pubKey.getParameters();
    ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(),
        domainParams.getN(), domainParams.getH());
    BCECPublicKey publicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec,
        BouncyCastleProvider.CONFIGURATION);
    return publicKey.getEncoded();
}
 
Example #29
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * openssl i2d_ECPrivateKey函数生成的DER编码的ecc私钥是:PKCS1标准的、带有EC_GROUP、带有公钥的,
 * 这个工具函数的主要目的就是为了使Java程序能够“识别”openssl生成的ECC私钥
 *
 * @param encodedKey
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
public static ECPrivateKeyParameters convertPkcs1DerToEcPriKey(byte[] encodedKey)
    throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(encodedKey);
    KeyFactory kf = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    BCECPrivateKey privateKey = (BCECPrivateKey) kf.generatePrivate(peks);
    ECParameterSpec ecParameterSpec = privateKey.getParameters();
    ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
        ecParameterSpec.getG(), ecParameterSpec.getN(), ecParameterSpec.getH());
    ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(privateKey.getD(),
        ecDomainParameters);
    return priKey;
}
 
Example #30
Source File: Wallet.java    From blockchain-java with Apache License 2.0 5 votes vote down vote up
/**
 * 创建新的密钥对
 *
 * @return
 * @throws Exception
 */
private KeyPair newECKeyPair() throws Exception {
    // 注册 BC Provider
    Security.addProvider(new BouncyCastleProvider());
    // 创建椭圆曲线算法的密钥对生成器,算法为 ECDSA
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
    // 椭圆曲线(EC)域参数设定
    // bitcoin 为什么会选择 secp256k1,详见:https://bitcointalk.org/index.php?topic=151120.0
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
    keyPairGenerator.initialize(ecSpec, new SecureRandom());
    return keyPairGenerator.generateKeyPair();
}