Java Code Examples for org.bouncycastle.crypto.params.ECPublicKeyParameters

The following examples show how to use org.bouncycastle.crypto.params.ECPublicKeyParameters. 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
Source Project: besu   Source File: SECP256K1.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean verifyDefault(
    final Bytes data, final Signature signature, final PublicKey pub) {
  final ECDSASigner signer = new ECDSASigner();
  final Bytes toDecode = Bytes.wrap(Bytes.of((byte) 4), pub.getEncodedBytes());
  final ECPublicKeyParameters params =
      new ECPublicKeyParameters(CURVE.getCurve().decodePoint(toDecode.toArrayUnsafe()), CURVE);
  signer.init(false, params);
  try {
    return signer.verifySignature(data.toArrayUnsafe(), signature.r, signature.s);
  } catch (final NullPointerException e) {
    // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those
    // signatures
    // are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
    return false;
  }
}
 
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: SM2KeyExchangeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param initiator         true表示发起方,false表示响应方
 * @param keyBits           生成的密钥长度
 * @param confirmationTag   确认信息,如果是响应方可以为null;如果是发起方则应为响应方的s1
 * @param selfStaticPriv    己方固定私钥
 * @param selfEphemeralPriv 己方临时私钥
 * @param selfId            己方ID
 * @param otherStaticPub    对方固定公钥
 * @param otherEphemeralPub 对方临时公钥
 * @param otherId           对方ID
 * @return
 */
public static ExchangeResult calculateKeyWithConfirmation(boolean initiator, int keyBits, byte[] confirmationTag,
    ECPrivateKeyParameters selfStaticPriv, ECPrivateKeyParameters selfEphemeralPriv, byte[] selfId,
    ECPublicKeyParameters otherStaticPub, ECPublicKeyParameters otherEphemeralPub, byte[] otherId) {
    SM2KeyExchange exch = new SM2KeyExchange();
    exch.init(new ParametersWithID(
        new SM2KeyExchangePrivateParameters(initiator, selfStaticPriv, selfEphemeralPriv),
        selfId));
    byte[][] result = exch.calculateKeyWithConfirmation(
        keyBits,
        confirmationTag,
        new ParametersWithID(new SM2KeyExchangePublicParameters(otherStaticPub, otherEphemeralPub), otherId));
    ExchangeResult confirmResult = new ExchangeResult();
    confirmResult.setKey(result[0]);
    if (initiator) {
        confirmResult.setS2(result[1]);
    } else {
        confirmResult.setS1(result[1]);
        confirmResult.setS2(result[2]);
    }
    return confirmResult;
}
 
Example 4
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 5
Source Project: gmhelper   Source File: SM2UtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSM2KeyRecovery() {
    try {
        String priHex = "5DD701828C424B84C5D56770ECF7C4FE882E654CAC53C7CC89A66B1709068B9D";
        String xHex = "FF6712D3A7FC0D1B9E01FF471A87EA87525E47C7775039D19304E554DEFE0913";
        String yHex = "F632025F692776D4C13470ECA36AC85D560E794E1BCCF53D82C015988E0EB956";
        String encodedPubHex = "04FF6712D3A7FC0D1B9E01FF471A87EA87525E47C7775039D19304E554DEFE0913F632025F692776D4C13470ECA36AC85D560E794E1BCCF53D82C015988E0EB956";
        String signHex = "30450220213C6CD6EBD6A4D5C2D0AB38E29D441836D1457A8118D34864C247D727831962022100D9248480342AC8513CCDF0F89A2250DC8F6EB4F2471E144E9A812E0AF497F801";
        byte[] signBytes = ByteUtils.fromHexString(signHex);
        byte[] src = ByteUtils.fromHexString("0102030405060708010203040506070801020304050607080102030405060708");
        byte[] withId = ByteUtils.fromHexString("31323334353637383132333435363738");

        ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
            new BigInteger(ByteUtils.fromHexString(priHex)), SM2Util.DOMAIN_PARAMS);
        ECPublicKeyParameters pubKey = BCECUtil.createECPublicKeyParameters(xHex, yHex, SM2Util.CURVE, SM2Util.DOMAIN_PARAMS);

        if (!SM2Util.verify(pubKey, src, signBytes)) {
            Assert.fail("verify failed");
        }
    } 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 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 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 8
Source Project: gmhelper   Source File: SM2UtilTest.java    License: 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 9
Source Project: littleca   Source File: Sm2KeyExchangeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param initiator true表示发起方,false表示响应方
 * @param keyBits 生成的密钥长度
 * @param confirmationTag 确认信息,如果是响应方可以为null;如果是发起方则应为响应方的s1
 * @param selfStaticPriv 己方固定私钥
 * @param selfEphemeralPriv 己方临时私钥
 * @param selfId 己方ID
 * @param otherStaticPub 对方固定公钥
 * @param otherEphemeralPub 对方临时公钥
 * @param otherId 对方ID
 * @return
 */
public static ExchangeResult calculateKeyWithConfirmation(boolean initiator, int keyBits, byte[] confirmationTag,
    ECPrivateKeyParameters selfStaticPriv, ECPrivateKeyParameters selfEphemeralPriv, byte[] selfId,
    ECPublicKeyParameters otherStaticPub, ECPublicKeyParameters otherEphemeralPub, byte[] otherId) {
    SM2KeyExchange exch = new SM2KeyExchange();
    exch.init(new ParametersWithID(
        new SM2KeyExchangePrivateParameters(initiator, selfStaticPriv, selfEphemeralPriv),
        selfId));
    byte[][] result = exch.calculateKeyWithConfirmation(
        keyBits,
        confirmationTag,
        new ParametersWithID(new SM2KeyExchangePublicParameters(otherStaticPub, otherEphemeralPub), otherId));
    ExchangeResult confirmResult = new ExchangeResult();
    confirmResult.setKey(result[0]);
    if (initiator) {
        confirmResult.setS2(result[1]);
    } else {
        confirmResult.setS1(result[1]);
        confirmResult.setS2(result[2]);
    }
    return confirmResult;
}
 
Example 10
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 11
Source Project: web3sdk   Source File: ECDSASigner.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(boolean forSigning, CipherParameters param) {
    SecureRandom providedRandom = null;

    if (forSigning) {
        if (param instanceof ParametersWithRandom) {
            ParametersWithRandom rParam = (ParametersWithRandom) param;

            this.key = (ECPrivateKeyParameters) rParam.getParameters();
            providedRandom = rParam.getRandom();
        } else {
            this.key = (ECPrivateKeyParameters) param;
        }
    } else {
        this.key = (ECPublicKeyParameters) param;
    }

    this.random =
            initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom);
}
 
Example 12
Source Project: fabric-api-archive   Source File: BouncyCastleCrypto.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(byte[] hash, byte[] signature, byte[] publicKey) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(publicKey), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 13
Source Project: incubator-tuweni   Source File: RLPxConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example 14
Source Project: InflatableDonkey   Source File: ECCurvePoint.java    License: MIT License 5 votes vote down vote up
public boolean verifySignature(byte[] message, BigInteger r, BigInteger s) {
    ECDomainParameters ecDomainParameters = ECAssistant.ecDomainParametersFrom(x9ECParameters);
    ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(Q, ecDomainParameters);

    ECDSASigner signer = new ECDSASigner();
    signer.init(false, ecPublicKeyParameters);

    return signer.verifySignature(message, r, s);
}
 
Example 15
Source Project: incubator-tuweni   Source File: SECP256K1.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the given ECDSA signature against the message bytes using the public key bytes.
 *
 * @param hash The keccak256 hash of the data to verify.
 * @param signature The signature.
 * @param publicKey The public key.
 * @return True if the verification is successful.
 */
public static boolean verifyHashed(byte[] hash, Signature signature, PublicKey publicKey) {
  ECDSASigner signer = new ECDSASigner();
  Bytes toDecode = Bytes.wrap(Bytes.of((byte) 4), publicKey.bytes());
  ECPublicKeyParameters params =
      new ECPublicKeyParameters(Parameters.CURVE.getCurve().decodePoint(toDecode.toArray()), Parameters.CURVE);
  signer.init(false, params);
  try {
    return signer.verifySignature(hash, signature.r, signature.s);
  } catch (NullPointerException e) {
    // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. Those signatures
    // are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
    return false;
  }
}
 
Example 16
Source Project: incubator-tuweni   Source File: SECP256K1.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculates an ECDH key agreement between the private and the public key of another party, formatted as a 32 bytes
 * array.
 *
 * @param privKey the private key
 * @param theirPubKey the public key
 * @return shared secret as 32 bytes
 */
public static Bytes32 calculateKeyAgreement(SecretKey privKey, PublicKey theirPubKey) {
  checkArgument(privKey != null, "missing private key");
  checkArgument(theirPubKey != null, "missing remote public key");

  ECPrivateKeyParameters privKeyP =
      new ECPrivateKeyParameters(privKey.bytes().toUnsignedBigInteger(), Parameters.CURVE);
  ECPublicKeyParameters pubKeyP = new ECPublicKeyParameters(theirPubKey.asEcPoint(), Parameters.CURVE);

  ECDHBasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privKeyP);
  return UInt256.valueOf(agreement.calculateAgreement(pubKeyP)).toBytes();
}
 
Example 17
Source Project: besu   Source File: SECP256K1.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculates an ECDH key agreement between the private and the public key.
 *
 * @param privKey The private key.
 * @param theirPubKey The public key.
 * @return The agreed secret.
 */
public static Bytes32 calculateECDHKeyAgreement(
    final PrivateKey privKey, final PublicKey theirPubKey) {
  checkArgument(privKey != null, "missing private key");
  checkArgument(theirPubKey != null, "missing remote public key");

  final ECPrivateKeyParameters privKeyP = new ECPrivateKeyParameters(privKey.getD(), CURVE);
  final ECPublicKeyParameters pubKeyP = new ECPublicKeyParameters(theirPubKey.asEcPoint(), CURVE);

  final ECDHBasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privKeyP);
  final BigInteger agreed = agreement.calculateAgreement(pubKeyP);

  return UInt256.valueOf(agreed).toBytes();
}
 
Example 18
Source Project: javasdk   Source File: ECKey.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p>
 * <p>
 * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be
 * larger than 520 bytes.</p>
 *
 * @param data      Hash of the data to verify.
 * @param signature signature.
 * @param pub       The public key bytes to use.
 * @return -
 */
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
    ECDSASigner signer = new ECDSASigner();
    ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE);
    signer.init(false, params);
    try {
        return signer.verifySignature(data, signature.r, signature.s);
    } catch (NullPointerException npe) {
        // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures.
        // Those signatures are inherently invalid/attack sigs so we just fail them here rather than crash the thread.
        logger.error("Caught NPE inside bouncy castle, " + npe);
        return false;
    }
}
 
Example 19
Source Project: javasdk   Source File: SMAccount.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean verify(byte[] sourceData, byte[] signature) {
    int lenSig = signature.length;
    if (signature[0] != 1 || lenSig <= 66) {
        throw new IllegalSignatureException();
    }
    byte[] realSig = new byte[lenSig - 66];
    System.arraycopy(signature, 66, realSig, 0, lenSig - 66);
    ECPublicKeyParameters ecPublicKeyParameters = (ECPublicKeyParameters) this.keyPair.getPublic();
    return SM2Util.verify(sourceData, realSig, ecPublicKeyParameters);
}
 
Example 20
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 21
Source Project: gmhelper   Source File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param xBytes           十六进制形式的公钥x分量,如果是SM2算法,应该是32字节
 * @param yBytes           十六进制形式的公钥y分量,如果是SM2算法,应该是32字节
 * @param curve            EC曲线参数,一般是固定的,如果是SM2算法的可参考{@link SM2Util#CURVE}
 * @param domainParameters EC Domain参数,一般是固定的,如果是SM2算法的可参考{@link SM2Util#DOMAIN_PARAMS}
 * @return
 */
public static ECPublicKeyParameters createECPublicKeyParameters(
        byte[] xBytes, byte[] yBytes, ECCurve curve, ECDomainParameters domainParameters) {
    final byte uncompressedFlag = 0x04;
    int curveLength = getCurveLength(domainParameters);
    xBytes = fixToCurveLengthBytes(curveLength, xBytes);
    yBytes = fixToCurveLengthBytes(curveLength, yBytes);
    byte[] encodedPubKey = new byte[1 + xBytes.length + yBytes.length];
    encodedPubKey[0] = uncompressedFlag;
    System.arraycopy(xBytes, 0, encodedPubKey, 1, xBytes.length);
    System.arraycopy(yBytes, 0, encodedPubKey, 1 + xBytes.length, yBytes.length);
    return new ECPublicKeyParameters(curve.decodePoint(encodedPubKey), domainParameters);
}
 
Example 22
Source Project: gmhelper   Source File: BCECUtil.java    License: 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 23
Source Project: gmhelper   Source File: SM2KeyExchangeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param initiator         true表示发起方,false表示响应方
 * @param keyBits           生成的密钥长度
 * @param selfStaticPriv    己方固定私钥
 * @param selfEphemeralPriv 己方临时私钥
 * @param selfId            己方ID
 * @param otherStaticPub    对方固定公钥
 * @param otherEphemeralPub 对方临时公钥
 * @param otherId           对方ID
 * @return 返回协商出的密钥,但是这个密钥是没有经过确认的
 */
public static byte[] calculateKey(boolean initiator, int keyBits,
    ECPrivateKeyParameters selfStaticPriv, ECPrivateKeyParameters selfEphemeralPriv, byte[] selfId,
    ECPublicKeyParameters otherStaticPub, ECPublicKeyParameters otherEphemeralPub, byte[] otherId) {
    SM2KeyExchange exch = new SM2KeyExchange();
    exch.init(new ParametersWithID(
        new SM2KeyExchangePrivateParameters(initiator, selfStaticPriv, selfEphemeralPriv),
        selfId));
    return exch.calculateKey(
        keyBits,
        new ParametersWithID(new SM2KeyExchangePublicParameters(otherStaticPub, otherEphemeralPub), otherId));
}
 
Example 24
Source Project: bop-bitcoin-client   Source File: ECKeyPair.java    License: 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 25
Source Project: jiguang-java-client-common   Source File: BCECUtil.java    License: 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 26
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 27
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 28
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 29
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 30
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();
    }
}