org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey Java Examples

The following examples show how to use org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey. 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: SM2PrivateKeyTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncoded() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyPair keyPair = SM2Util.generateKeyPair();
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();
    SM2PublicKey sm2PublicKey = new SM2PublicKey(publicKey.getAlgorithm(), publicKey);
    SM2PrivateKey sm2PrivateKey1 = new SM2PrivateKey(privateKey, publicKey);
    SM2PrivateKey sm2PrivateKey2 = new SM2PrivateKey(privateKey, sm2PublicKey);
    String nativePriDER = ByteUtils.toHexString(privateKey.getEncoded());
    String sm2PriDER1 = ByteUtils.toHexString(sm2PrivateKey1.getEncoded());
    String sm2PriDER2 = ByteUtils.toHexString(sm2PrivateKey2.getEncoded());
    if (nativePriDER.equalsIgnoreCase(sm2PriDER1)) {
        Assert.fail();
    }
    if (!sm2PriDER1.equalsIgnoreCase(sm2PriDER2)) {
        Assert.fail();
    }
    System.out.println("Native EC Private Key DER:\n" + nativePriDER.toUpperCase());
    System.out.println("SM2 EC Private Key DER:\n" + sm2PriDER1.toUpperCase());
}
 
Example #2
Source File: NamedCurveTest.java    From UAF with Apache License 2.0 6 votes vote down vote up
@Test
public void valuesFromExample() throws IOException, Exception {
	String privKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgzqOJl-rC0FFMMFM7w7sqp99jsBxgMx_fqwuaUc4CVv-gCgYIKoZIzj0DAQehRANCAAQokXIHgAc20GWpznnnIX9eD2btK-R-uWUFgOKt8l27RcrrOrqJ66uCMfOuG4I1usUUOa7f_A19v74FC-HuSB50";
	String pubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKJFyB4AHNtBlqc555yF_Xg9m7SvkfrllBYDirfJdu0XK6zq6ieurgjHzrhuCNbrFFDmu3_wNfb--BQvh7kgedA==";

	PublicKey pub = KeyCodec.getPubKey(Base64.decodeBase64(pubKey));
	PrivateKey priv = KeyCodec.getPrivKey(Base64.decodeBase64(privKey));

	String dataForSigningStr = "BD6OAA==";
	byte[] dataForSigning = Base64.decodeBase64(dataForSigningStr);

	BigInteger[] signatureGen = NamedCurve.signAndFromatToRS(priv,
			dataForSigning);

	byte[] asn1EncodedSignature = Asn1.getEncoded(signatureGen);
	logger.info("asn1EncodedSignature="
			+ Base64.encodeBase64URLSafeString(asn1EncodedSignature));
	assertTrue(NamedCurve.verify(
			KeyCodec.getKeyAsRawBytes((BCECPublicKey) pub), dataForSigning,
			Asn1.decodeToBigIntegerArray(asn1EncodedSignature)));
}
 
Example #3
Source File: Certificate.java    From oxAuth with MIT License 6 votes vote down vote up
public PublicKey getPublicKey() {
    PublicKey publicKey = null;

    if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCRSAPublicKey) {
        BCRSAPublicKey jcersaPublicKey = (BCRSAPublicKey) x509Certificate.getPublicKey();

        publicKey = new RSAPublicKey(jcersaPublicKey.getModulus(), jcersaPublicKey.getPublicExponent());
    } else if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCECPublicKey) {
        BCECPublicKey jceecPublicKey = (BCECPublicKey) x509Certificate.getPublicKey();

        publicKey = new ECDSAPublicKey(signatureAlgorithm, jceecPublicKey.getQ().getXCoord().toBigInteger(),
                jceecPublicKey.getQ().getYCoord().toBigInteger());
    }

    return publicKey;
}
 
Example #4
Source File: Account.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
public byte[] serializePublicKey() {
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    BCECPublicKey pub = (BCECPublicKey) publicKey;
    try {
        switch (this.keyType) {
            case ECDSA:
                //bs.write(this.keyType.getLabel());
                //bs.write(Curve.valueOf(pub.getParameters().getCurve()).getLabel());
                bs.write(pub.getQ().getEncoded(true));
                break;
            case SM2:
                bs.write(this.keyType.getLabel());
                bs.write(Curve.valueOf(pub.getParameters().getCurve()).getLabel());
                bs.write(pub.getQ().getEncoded(true));
                break;
            default:
                // Should not reach here
                throw new Exception(ErrorCode.UnknownKeyType);
        }
    } catch (Exception e) {
        // Should not reach here
        e.printStackTrace();
        return null;
    }
    return bs.toByteArray();
}
 
Example #5
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generate a new keypair using the given Java Security Provider.
 * <p>
 * All private key operations will use the provider.
 */
public ECKey(Provider provider, SecureRandom secureRandom) {
    this.provider = provider;

    final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom);
    final KeyPair keyPair = keyPairGen.generateKeyPair();

    this.privKey = keyPair.getPrivate();

    final PublicKey pubKey = keyPair.getPublic();
    this.publicKey = keyPair.getPublic();
    if (pubKey instanceof BCECPublicKey) {
        pub = ((BCECPublicKey) pubKey).getQ();
    } else if (pubKey instanceof ECPublicKey) {
        pub = extractPublicKey((ECPublicKey) pubKey);
    } else {
        throw new AssertionError(
                "Expected Provider " + provider.getName() +
                        " to produce a subtype of ECPublicKey, found " + pubKey.getClass());
    }
}
 
Example #6
Source File: SECP256K1.java    From besu with Apache License 2.0 6 votes vote down vote up
public static KeyPair generate() {
  final java.security.KeyPair rawKeyPair = KEY_PAIR_GENERATOR.generateKeyPair();
  final BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  final BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  final BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  final byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  final BigInteger publicKeyValue =
      new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(PrivateKey.create(privateKeyValue), PublicKey.create(publicKeyValue));
}
 
Example #7
Source File: BlockDataGenerator.java    From besu with Apache License 2.0 6 votes vote down vote up
private SECP256K1.KeyPair generateKeyPair() {
  final java.security.KeyPair rawKeyPair = keyPairGenerator.generateKeyPair();
  final BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  final BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  final BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  final byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  final BigInteger publicKeyValue =
      new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new SECP256K1.KeyPair(
      SECP256K1.PrivateKey.create(privateKeyValue), SECP256K1.PublicKey.create(publicKeyValue));
}
 
Example #8
Source File: ECKeyPair.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * create ECKeyPair from KeyPair
 *
 * @param keyPair
 * @return
 */
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    ECKeyPair ecKeyPair = new ECKeyPair(privateKeyValue, publicKeyValue);
    return ecKeyPair;
}
 
Example #9
Source File: Wallet.java    From blockchain-java with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化钱包
 */
private void initWallet() {
    try {
        KeyPair keyPair = newECKeyPair();
        BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
        BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

        byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);

        this.setPrivateKey(privateKey);
        this.setPublicKey(publicKeyBytes);
    } catch (Exception e) {
        log.error("Fail to init wallet ! ", e);
        throw new RuntimeException("Fail to init wallet ! ", e);
    }
}
 
Example #10
Source File: SECP256K1.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair.
 *
 * Entropy for the generation is drawn from {@link SecureRandom}.
 *
 * @return A new keypair.
 */
public static KeyPair random() {
  java.security.KeyPair rawKeyPair = Parameters.KEY_PAIR_GENERATOR.generateKeyPair();
  BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(SecretKey.fromInteger(privateKeyValue), PublicKey.fromInteger(publicKeyValue));
}
 
Example #11
Source File: SM2UtilTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateBCECKeyPair() {
    try {
        KeyPair keyPair = SM2Util.generateKeyPair();
        ECPrivateKeyParameters priKey = BCECUtil.convertPrivateKeyToParameters((BCECPrivateKey) keyPair.getPrivate());
        ECPublicKeyParameters pubKey = BCECUtil.convertPublicKeyToParameters((BCECPublicKey) keyPair.getPublic());

        byte[] sign = SM2Util.sign(priKey, WITH_ID, SRC_DATA);
        boolean flag = SM2Util.verify(pubKey, WITH_ID, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }

        sign = SM2Util.sign(priKey, SRC_DATA);
        flag = SM2Util.verify(pubKey, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #12
Source File: SM2PfxMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakePfx() {
    try {
        KeyPair subKP = SM2Util.generateKeyPair();
        X500Name subDN = SM2X509CertMakerTest.buildSubjectDN();
        SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(),
            (BCECPublicKey) subKP.getPublic());
        byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(),
            SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded();
        SM2X509CertMaker certMaker = SM2X509CertMakerTest.buildCertMaker();
        X509Certificate cert = certMaker.makeSSLEndEntityCert(csr);

        SM2PfxMaker pfxMaker = new SM2PfxMaker();
        PKCS10CertificationRequest request = new PKCS10CertificationRequest(csr);
        PublicKey subPub = BCECUtil.createPublicKeyFromSubjectPublicKeyInfo(request.getSubjectPublicKeyInfo());
        PKCS12PfxPdu pfx = pfxMaker.makePfx(subKP.getPrivate(), subPub, cert, TEST_PFX_PASSWD);
        byte[] pfxDER = pfx.getEncoded(ASN1Encoding.DER);
        FileUtil.writeFile(TEST_PFX_FILENAME, pfxDER);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #13
Source File: SM2PfxMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testPfxSign() {
    //先生成一个pfx
    testMakePfx();

    try {
        byte[] pkcs12 = FileUtil.readFile(TEST_PFX_FILENAME);
        BCECPublicKey publicKey = SM2CertUtil.getPublicKeyFromPfx(pkcs12, TEST_PFX_PASSWD);
        BCECPrivateKey privateKey = SM2CertUtil.getPrivateKeyFromPfx(pkcs12, TEST_PFX_PASSWD);

        String srcData = "1234567890123456789012345678901234567890";
        byte[] sign = SM2Util.sign(privateKey, srcData.getBytes());
        boolean flag = SM2Util.verify(publicKey, srcData.getBytes(), sign);
        if (!flag) {
            Assert.fail();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #14
Source File: SM2X509CertMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakeCertificate() {
    try {
        KeyPair subKP = SM2Util.generateKeyPair();
        X500Name subDN = buildSubjectDN();
        SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(),
            (BCECPublicKey) subKP.getPublic());
        byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(),
            SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded();
        savePriKey("target/test.sm2.pri", (BCECPrivateKey) subKP.getPrivate(),
            (BCECPublicKey) subKP.getPublic());
        SM2X509CertMaker certMaker = buildCertMaker();
        X509Certificate cert = certMaker.makeSSLEndEntityCert(csr);
        FileUtil.writeFile("target/test.sm2.cer", cert.getEncoded());
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #15
Source File: SM2Pkcs12MakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakePkcs12() {
    try {
        KeyPair subKP = SM2Util.generateKeyPair();
        X500Name subDN = SM2X509CertMakerTest.buildSubjectDN();
        SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(),
            (BCECPublicKey) subKP.getPublic());
        byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(),
            SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded();
        SM2X509CertMaker certMaker = SM2X509CertMakerTest.buildCertMaker();
        X509Certificate cert = certMaker.makeSSLEndEntityCert(csr);

        SM2Pkcs12Maker pkcs12Maker = new SM2Pkcs12Maker();
        KeyStore pkcs12 = pkcs12Maker.makePkcs12(subKP.getPrivate(), cert, TEST_P12_PASSWD);
        try (OutputStream os = Files.newOutputStream(Paths.get(TEST_P12_FILENAME),
                                    StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            pkcs12.store(os, TEST_P12_PASSWD);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #16
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair.
 *
 * Entropy for the generation is drawn from {@link SecureRandom}.
 *
 * @return A new keypair.
 */
public static KeyPair random() {
  java.security.KeyPair rawKeyPair = Parameters.KEY_PAIR_GENERATOR.generateKeyPair();
  BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(SecretKey.fromInteger(privateKeyValue), PublicKey.fromInteger(publicKeyValue));
}
 
Example #17
Source File: ECKeyPair.java    From blockchain with Apache License 2.0 5 votes vote down vote up
public ECKeyPair(PrivateKey privateKey, PublicKey publicKey) {
    this.privateKey = privateKey;
    this.publicKey = publicKey;
    // 生成 BigInteger 形式的公钥和私钥
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) this.privateKey;
    BCECPublicKey bcecPublicKey = (BCECPublicKey) this.publicKey;
    // 分别计算公钥和私钥的值
    BigInteger privateKeyValue = bcecPrivateKey.getD();
    byte[] publicKeyBytes = bcecPublicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));
    this.privateKeyValue = privateKeyValue;
    this.publicKeyValue = publicKeyValue;
}
 
Example #18
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 #19
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 #20
Source File: MultiSigScriptHashInputTest.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
private static ECKey generateKey() {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDsA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
        keyGen.initialize(ecSpec, new SecureRandom());
        KeyPair generateKeyPair = keyGen.generateKeyPair();

        BCECPrivateKey private1 = (BCECPrivateKey) generateKeyPair.getPrivate();
        BCECPublicKey public1 = (BCECPublicKey) generateKeyPair.getPublic();
        String X = public1.engineGetQ().getAffineXCoord().toBigInteger().toString(16);
        String Y = public1.engineGetQ().getAffineYCoord().toBigInteger().toString(16);

        // format string to 64 length with zero in head

        String x = formatStringAdd0(X, 64);
        String y = formatStringAdd0(Y, 64);

        // public key string
        String publicKeyStr = "04" + x + y;

        // set public key begin with 04
        return new ECKey(private1.getS().toByteArray(), false, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #21
Source File: NamedCurveTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
	public void testRawPubKey() throws Exception{
		String privKey = 
//				"UhCeQEsqYcby7UfjKWLxGePlag/RUTIAwYypF0K3ERU=";
				"nXCriWW3w9msxnrtOQYlYb+R51pI8zZyLTLhR8hxggk=";
		String pubKey = 
//				"BK4Qk0tQwU3zSfStH0ZTMKzC6ZfF3PBEqoGLWwJMYQVzvncvr8fv+S6POJ96oLZn0l4YS/OpqB19Of+l1qxwO9Q=";
				"BOg4fylDlzNxMFFTvtQBRsakfxaBJBPJf25sx8Iaim8v3h0ml9mnNCrUVJjBAeXyeGAX69NbAxbaAkNHT+6gJtU=";

		byte[] privKeyBytes = Base64.decodeBase64(privKey);
		byte[] pubKeysBytes = Base64.decodeBase64(pubKey);
		
		PublicKey pub = KeyCodec.getPubKeyFromCurve(pubKeysBytes, "secp256r1");
		PrivateKey priv = KeyCodec.getPrivKeyFromCurve(privKeyBytes, "secp256r1");
		assertNotNull(pub);
		assertNotNull(priv);
		
		String signature = "MEQCIAwtk4DStr2MqkrAlOVG+nyQxbS6tnBpVi7OcKCm8/5lAiBjVsv+b+7nI/306iNHrso/ruOaxY8IJy3jw2/zr17JEQ==";
		BigInteger[] rs = Asn1.decodeToBigIntegerArray(Base64.decodeBase64(signature));
		
		byte[] dataForSigning = Base64.decodeBase64("VGhpcyBpcyBzb21lIHJhbmRvbSBkYXRhIHRvIGJlIHNpZ25lZCBieSBhIHByaXZhdGUga2V5IGFuZCB0aGVuIHZlcmlmaWVkLg");
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(dataForSigning);
		dataForSigning = md.digest();
		boolean verify = NamedCurve.verify(KeyCodec.getKeyAsRawBytes((BCECPublicKey)pub), dataForSigning, rs);
		assertTrue(verify);
	}
 
Example #22
Source File: ECKeyPair.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    return new ECKeyPair(privateKeyValue, publicKeyValue);
}
 
Example #23
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 #24
Source File: SM2Util.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
/**
 * 只获取公钥里的XY分量,64字节
 *
 * @param publicKey
 * @return
 */
public static byte[] getRawPublicKey(BCECPublicKey publicKey) {
    byte[] src65 = publicKey.getQ().getEncoded(false);
    byte[] rawXY = new byte[CURVE_LEN * 2];//SM2的话这里应该是64字节
    System.arraycopy(src65, 1, rawXY, 0, rawXY.length);
    return rawXY;
}
 
Example #25
Source File: ECCEncrypt.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * create BCECPublicKey from publicKey and privateKey
 *
 * @param publicKey
 * @return
 */
private BCECPublicKey createBCECPublicKey(BigInteger publicKey) {
    // Handle public key.
    String publicKeyValue =
            Numeric.toHexStringNoPrefixZeroPadded(publicKey, Keys.PUBLIC_KEY_LENGTH_IN_HEX);
    String prePublicKeyStr = publicKeyValue.substring(0, 64);
    String postPublicKeyStr = publicKeyValue.substring(64);
    SecP256K1Curve secP256K1Curve = new SecP256K1Curve();
    SecP256K1Point secP256K1Point =
            (SecP256K1Point)
                    secP256K1Curve.createPoint(
                            new BigInteger(prePublicKeyStr, 16),
                            new BigInteger(postPublicKeyStr, 16));
    SecP256K1Point secP256K1PointG =
            (SecP256K1Point)
                    secP256K1Curve.createPoint(ECCParams.POINTG_PRE, ECCParams.POINTG_POST);

    ECDomainParameters domainParameters =
            new ECDomainParameters(secP256K1Curve, secP256K1PointG, ECCParams.FACTOR_N);
    ECPublicKeyParameters publicKeyParameters =
            new ECPublicKeyParameters(secP256K1Point, domainParameters);

    BCECPublicKey bcecPublicKey =
            new BCECPublicKey(
                    "ECDSA",
                    publicKeyParameters,
                    ECCParams.ecNamedCurveSpec,
                    BouncyCastleProvider.CONFIGURATION);

    return bcecPublicKey;
}
 
Example #26
Source File: ECKeyPair.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    return new ECKeyPair(privateKeyValue, publicKeyValue);
}
 
Example #27
Source File: SM2CertUtilTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBCECPublicKey() {
    try {
        //当前测试例依赖以下测试例生成的文件,所以先调用一下
        new SM2X509CertMakerTest().testMakeCertificate();

        X509Certificate cert = SM2CertUtil.getX509Certificate("target/test.sm2.cer");
        BCECPublicKey pubKey = SM2CertUtil.getBCECPublicKey(cert);
        byte[] priKeyData = FileUtil.readFile("target/test.sm2.pri");
        ECPrivateKeyParameters priKeyParameters = BCECUtil.convertSEC1ToECPrivateKey(priKeyData);

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

        sign = SM2Util.sign(priKeyParameters, GMBaseTest.SRC_DATA);
        System.out.println("SM2 sign without withId result:\n" + ByteUtils.toHexString(sign));
        flag = SM2Util.verify(pubKey, GMBaseTest.SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }

        byte[] cipherText = SM2Util.encrypt(pubKey, GMBaseTest.SRC_DATA);
        System.out.println("SM2 encrypt result:\n" + ByteUtils.toHexString(cipherText));
        byte[] plain = SM2Util.decrypt(priKeyParameters, cipherText);
        System.out.println("SM2 decrypt result:\n" + ByteUtils.toHexString(plain));
        if (!Arrays.equals(plain, GMBaseTest.SRC_DATA)) {
            Assert.fail("plain not equals the src");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #28
Source File: Certificate.java    From oxAuth with MIT License 5 votes vote down vote up
public ECDSAPublicKey getEcdsaPublicKey() {
    ECDSAPublicKey ecdsaPublicKey = null;

    if (x509Certificate != null && x509Certificate.getPublicKey() instanceof BCECPublicKey) {
        BCECPublicKey publicKey = (BCECPublicKey) x509Certificate.getPublicKey();

        ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, publicKey.getQ().getXCoord().toBigInteger(),
                publicKey.getQ().getYCoord().toBigInteger());
    }

    return ecdsaPublicKey;
}
 
Example #29
Source File: CertTools.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
 * getPublicKey
 * @param key
 * @return String
 */
public static String getPublicKeyString(PublicKey key) {
    //        ECPublicKeyImpl pub = (ECPublicKeyImpl) key;
    BCECPublicKey bcecPublicKey = (BCECPublicKey) key;
    byte[] bcecPubBytes = bcecPublicKey.getEncoded();
    String publicKey = Numeric.toHexStringNoPrefix(bcecPubBytes);
    publicKey = publicKey.substring(publicKey.length() - PUBLIC_KEY_IN_HEX_LENGTH); //只取后128位
    return publicKey;
}
 
Example #30
Source File: Sm2KeyPairImpl.java    From littleca with Apache License 2.0 5 votes vote down vote up
public Sm2KeyPairImpl() {
	  try {
		  KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC");
		  //参见 SM2P256V1Curve GMObjectIdentifiers
		  g.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1"));
		  KeyPair p = g.generateKeyPair();
	
		  PrivateKey privKey = p.getPrivate();
		  PublicKey pubKey = p.getPublic();
		  publicKey=new Sm2PublicKeyImpl( (BCECPublicKey) pubKey);
		  privateKey=new Sm2PrivateKeyImpl((BCECPrivateKey) privKey);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}