org.bouncycastle.crypto.params.ECPublicKeyParameters Java Examples

The following examples show how to use org.bouncycastle.crypto.params.ECPublicKeyParameters. 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: SM2UtilTest.java    From gmhelper with 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 #2
Source File: SM2KeyExchangeUtil.java    From gmhelper with 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 #3
Source File: Sm2KeyExchangeUtil.java    From littleca with 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 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 #5
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 #6
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 #7
Source File: ECDSASigner.java    From web3sdk with 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 #8
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 #9
Source File: SM2UtilTest.java    From gmhelper with 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 #10
Source File: SECP256K1.java    From besu with 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 #11
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 #12
Source File: BouncyCastleCrypto.java    From fabric-api-archive with 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 File: ShareSecretTest.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Test
public void test() {
    ECPrivateKeyParameters privKeyA = new ECPrivateKeyParameters(
            new BigInteger(1, HexUtil.decode("8653b44d4acebec2cd64a015b2e509c70c9049a692e71b08fe7f52cc1fa5595f")), CURVE);
    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
    agreement.init(privKeyA);
    ECPublicKeyParameters pubKeyB = new ECPublicKeyParameters(
            CURVE.getCurve().decodePoint(HexUtil.decode("02fd82681e79fbe293aef1a48c6c9b1252591340bb46de1444ad5de400ff84a433")), CURVE);
    BigInteger result = agreement.calculateAgreement(pubKeyB);
    byte[] sharedSecret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), result);
    System.out.println(HexUtil.encode(sharedSecret));
    // sharedSecret hex string: 692c40fdbe605b9966beee978ab290e7a35056dffe9ed092a87e62fce468791d
}
 
Example #14
Source File: Ts3Crypt.java    From ts3j with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignature(ECPoint publicKey, byte[] data, byte[] signature) {
    DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest());
    ECPublicKeyParameters signingKey = new ECPublicKeyParameters(publicKey, getDomainParameters());

    signer.init(false, signingKey);
    signer.update(data, 0, data.length);

    return signer.verifySignature(signature);
}
 
Example #15
Source File: ECKey.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public boolean verify(byte[] message, byte[] signature) throws Exception
{
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    ECDSASigner signer = new ECDSASigner();
    //not for signing...
    signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(pub), params));
    DLSequence seq = (DLSequence) asn1.readObject();
    BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getPositiveValue();
    BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getPositiveValue();
    return signer.verifySignature(message, r, s);
}
 
Example #16
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 #17
Source File: DSAPlainDigestSigner.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public void init(boolean forSigning, CipherParameters parameters) {
  this.forSigning = forSigning;

  AsymmetricKeyParameter param = (parameters instanceof ParametersWithRandom)
      ? (AsymmetricKeyParameter) ((ParametersWithRandom) parameters).getParameters()
      : (AsymmetricKeyParameter) parameters;

  Args.notNull(param, "param");
  if (param instanceof ECPublicKeyParameters) {
    keyBitLen = ((ECPublicKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof ECPrivateKeyParameters) {
    keyBitLen = ((ECPrivateKeyParameters) param).getParameters().getCurve().getFieldSize();
  } else if (param instanceof DSAPublicKeyParameters) {
    keyBitLen = ((DSAPublicKeyParameters) param).getParameters().getQ().bitLength();
  } else if (param instanceof DSAPrivateKeyParameters) {
    keyBitLen = ((DSAPrivateKeyParameters) param).getParameters().getQ().bitLength();
  } else {
    throw new IllegalArgumentException("unknown parameters: " + param.getClass().getName());
  }

  if (forSigning && !param.isPrivate()) {
    throw new IllegalArgumentException("Signing Requires Private Key.");
  }

  if (!forSigning && param.isPrivate()) {
    throw new IllegalArgumentException("Verification Requires Public Key.");
  }

  reset();
  dsaSigner.init(forSigning, parameters);
}
 
Example #18
Source File: ECKeyPair.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Verify a hash with the private key of this key pair.
 *
 * @param hash
 * @param signature
 * @return
 */
public boolean verify(byte[] hash, ECDSASignature signature) {
    ECDSASigner signer = new ECDSASigner();
    // not for signing...
    signer.init(
            false,
            new ECPublicKeyParameters(
                    Sign.publicPointFromPrivate(getPrivateKey()), Sign.CURVE));
    return signer.verifySignature(hash, signature.r, signature.s);
}
 
Example #19
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 #20
Source File: ECCurvePoint.java    From InflatableDonkey with 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 #21
Source File: Sign1MessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws CoseException {

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

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

    key = CBORObject.NewMap();
    key.Add(KeyKeys.KeyType.AsCBOR(), KeyKeys.KeyType_EC2);
    key.Add(KeyKeys.EC2_Curve.AsCBOR(), KeyKeys.EC2_P256);
    key.Add(KeyKeys.EC2_D.AsCBOR(), rgbD);
    cnKeyPrivate = new OneKey(key);
}
 
Example #22
Source File: Signer.java    From evt4j with MIT License 5 votes vote down vote up
/**
 * return true if the value r and s represent a DSA signature for the passed in
 * message (for standard DSA the message should be a SHA-1 hash of the real
 * message to be verified).
 */
@Override
public boolean verifySignature(byte[] message, BigInteger r, BigInteger s) {
    ECDomainParameters ec = key.getParameters();
    BigInteger n = ec.getN();
    BigInteger e = calculateE(n, message);

    // r in the range [1,n-1]
    if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) {
        return false;
    }

    // s in the range [1,n-1]
    if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) {
        return false;
    }

    BigInteger c = s.modInverse(n);

    BigInteger u1 = e.multiply(c).mod(n);
    BigInteger u2 = r.multiply(c).mod(n);

    ECPoint G = ec.getG();
    ECPoint Q = ((ECPublicKeyParameters) key).getQ();

    ECPoint point = ECAlgorithms.sumOfTwoMultiplies(G, u1, Q, u2).normalize();

    // components must be bogus.
    if (point.isInfinity()) {
        return false;
    }

    BigInteger v = point.getAffineXCoord().toBigInteger().mod(n);

    return v.equals(r);
}
 
Example #23
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

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

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #24
Source File: RLPxConnectionFactory.java    From cava with 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 #25
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 #26
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是PKCS1标准的,
 * 这个工具函数的主要目的就是为了能生成一个openssl可以“识别”的ECC私钥
 *
 * @param priKey
 * @param pubKey
 * @return
 * @throws IOException
 */
public static byte[] convertEcPriKeyToPkcs1Der(ECPrivateKeyParameters priKey,
                                               ECPublicKeyParameters pubKey) throws IOException {
    byte[] pkcs8Bytes = convertEcPriKeyToPkcs8Der(priKey, pubKey);
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
    ASN1Encodable encodable = pki.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    byte[] pkcs1Bytes = primitive.getEncoded();
    return pkcs1Bytes;
}
 
Example #27
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static ECPublicKeyParameters createEcPublicKey(byte[] xBytes, byte[] yBytes,
                                                      ECCurve curve, ECDomainParameters domainParameters) {
    final byte uncompressedFlag = 0x04;
    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 #28
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static boolean verifyUsingSecp256k1(byte[] pub, byte[] dataForSigning,
		BigInteger[] rs) throws Exception {
	ECDSASigner signer = new ECDSASigner();
	X9ECParameters params = SECNamedCurves.getByName("secp256k1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	ECPublicKeyParameters pubKeyParams = new ECPublicKeyParameters(ecParams
			.getCurve().decodePoint(pub), ecParams);
	signer.init(false, pubKeyParams);

	return signer.verifySignature(dataForSigning, rs[0].abs(), rs[1].abs());
}
 
Example #29
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 #30
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;
}