org.bouncycastle.asn1.x9.X9ECParameters Java Examples

The following examples show how to use org.bouncycastle.asn1.x9.X9ECParameters. 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: BCECUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
/**
 * copy from BC
 *
 * @param curveName
 * @return
 */
public static X9ECParameters getDomainParametersFromName(String curveName) {
    X9ECParameters domainParameters;
    try {
        if (curveName.charAt(0) >= '0' && curveName.charAt(0) <= '2') {
            ASN1ObjectIdentifier oidID = new ASN1ObjectIdentifier(curveName);
            domainParameters = ECUtil.getNamedCurveByOid(oidID);
        } else {
            if (curveName.indexOf(' ') > 0) {
                curveName = curveName.substring(curveName.indexOf(' ') + 1);
                domainParameters = ECUtil.getNamedCurveByName(curveName);
            } else {
                domainParameters = ECUtil.getNamedCurveByName(curveName);
            }
        }
    } catch (IllegalArgumentException ex) {
        domainParameters = ECUtil.getNamedCurveByName(curveName);
    }
    return domainParameters;
}
 
Example #2
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @description 创建私钥和公钥
 * 
 * @return 私钥
 */
public static byte[] generatorPrivateKey() {
	int length = 0;
	byte[] privateKey;
	do {
		ECKeyPairGenerator gen = new ECKeyPairGenerator();
		SecureRandom secureRandom = new SecureRandom();
		X9ECParameters secnamecurves = SECNamedCurves.getByName("secp256k1");
		ECDomainParameters ecParams = new ECDomainParameters(secnamecurves.getCurve(), secnamecurves.getG(),
				secnamecurves.getN(), secnamecurves.getH());
		ECKeyGenerationParameters keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);
		gen.init(keyGenParam);
		AsymmetricCipherKeyPair kp = gen.generateKeyPair();
		ECPrivateKeyParameters privatekey = (ECPrivateKeyParameters) kp.getPrivate();
		privateKey = privatekey.getD().toByteArray();
		length = privatekey.getD().toByteArray().length;
	} while (length != 32);
	return privateKey;
}
 
Example #3
Source File: ECDHExportTest.java    From Encryptor4j with MIT License 6 votes vote down vote up
@Test
public void testExportImport() throws GeneralSecurityException {

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

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

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

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

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

	Assert.assertArrayEquals(ecPublicKey.getEncoded(), importedECPublicKey.getEncoded());
}
 
Example #4
Source File: GMUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static byte[] getSM2Z(byte[] userID, ASN1ObjectIdentifier curveOid,
    BigInteger pubPointX, BigInteger pubPointY) {
  SM3Digest digest = new SM3Digest();

  addUserId(digest, userID);

  X9ECParameters ecParams = GMNamedCurves.getByOID(curveOid);
  addFieldElement(digest, ecParams.getCurve().getA());
  addFieldElement(digest, ecParams.getCurve().getB());
  addFieldElement(digest, ecParams.getG().getAffineXCoord());
  addFieldElement(digest, ecParams.getG().getAffineYCoord());

  int fieldSize = (ecParams.getCurve().getFieldSize() + 7) / 8;
  byte[] bytes = BigIntegers.asUnsignedByteArray(fieldSize, pubPointX);
  digest.update(bytes, 0, fieldSize);

  bytes = BigIntegers.asUnsignedByteArray(fieldSize, pubPointY);
  digest.update(bytes, 0, fieldSize);

  byte[] result = new byte[digest.getDigestSize()];
  digest.doFinal(result, 0);
  return result;
}
 
Example #5
Source File: SHA256withECDSASignatureVerification.java    From oxAuth with MIT License 6 votes vote down vote up
@Override
 public PublicKey decodePublicKey(byte[] encodedPublicKey) throws SignatureException {
         X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
         ECPoint point = curve.getCurve().decodePoint(encodedPublicKey);

         try {
	return KeyFactory.getInstance("ECDSA").generatePublic(
	        new ECPublicKeySpec(point,
	                new ECParameterSpec(
	                        curve.getCurve(),
	                        curve.getG(),
	                        curve.getN(),
	                        curve.getH()
	                )
	        )
	);
} catch (GeneralSecurityException ex) {
	throw new SignatureException(ex);
}
 }
 
Example #6
Source File: ECPrivateKeyImportCompact.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }


    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);
    BigInteger d = BigIntegers.fromUnsignedByteArray(data, fieldLength, fieldLength);

    return ECKeyFactories.privateKeyFactory()
            .createECPrivateKey(x, y, d, curveName);
}
 
Example #7
Source File: DataStore.java    From athenz with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
String getCurveName(org.bouncycastle.jce.spec.ECParameterSpec ecParameterSpec, boolean rfc) {

    String curveName = null;
    for (Enumeration names = ECNamedCurveTable.getNames(); names.hasMoreElements();) {

        final String name = (String) names.nextElement();
        final X9ECParameters params = ECNamedCurveTable.getByName(name);

        if (params.getN().equals(ecParameterSpec.getN())
                && params.getH().equals(ecParameterSpec.getH())
                && params.getCurve().equals(ecParameterSpec.getCurve())
                && params.getG().equals(ecParameterSpec.getG())) {
            curveName = name;
            break;
        }
    }

    return rfc ? rfcEllipticCurveName(curveName) : curveName;
}
 
Example #8
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 6 votes vote down vote up
/**
 * copy from BC
 *
 * @param curveName
 * @return
 */
public static X9ECParameters getDomainParametersFromName(String curveName) {
    X9ECParameters domainParameters;
    try {
        if (curveName.charAt(0) >= '0' && curveName.charAt(0) <= '2') {
            ASN1ObjectIdentifier oidID = new ASN1ObjectIdentifier(curveName);
            domainParameters = ECUtil.getNamedCurveByOid(oidID);
        } else {
            if (curveName.indexOf(' ') > 0) {
                curveName = curveName.substring(curveName.indexOf(' ') + 1);
                domainParameters = ECUtil.getNamedCurveByName(curveName);
            } else {
                domainParameters = ECUtil.getNamedCurveByName(curveName);
            }
        }
    } catch (IllegalArgumentException ex) {
        domainParameters = ECUtil.getNamedCurveByName(curveName);
    }
    return domainParameters;
}
 
Example #9
Source File: PublicKeyChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void checkECSubjectPublicKeyInfo(ASN1ObjectIdentifier curveOid, byte[] encoded)
    throws BadCertTemplateException {
  Integer expectedLength = EC_CURVEFIELD_SIZES.get(curveOid);
  if (expectedLength == null) {
    X9ECParameters ecP = ECUtil.getNamedCurveByOid(curveOid);
    ECCurve curve = ecP.getCurve();
    expectedLength = (curve.getFieldSize() + 7) / 8;
    EC_CURVEFIELD_SIZES.put(curveOid, expectedLength);
  }

  switch (encoded[0]) {
    case 0x02: // compressed
    case 0x03: // compressed
      if (encoded.length != (expectedLength + 1)) {
        throw new BadCertTemplateException("incorrect length for compressed encoding");
      }
      break;
    case 0x04: // uncompressed
    case 0x06: // hybrid
    case 0x07: // hybrid
      if (encoded.length != (2 * expectedLength + 1)) {
        throw new BadCertTemplateException("incorrect length for uncompressed/hybrid encoding");
      }
      break;
    default:
      throw new BadCertTemplateException(
          "invalid point encoding 0x" + Integer.toString(encoded[0], 16));
  } // end switch
}
 
Example #10
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static void checkEcSubjectPublicKeyInfo(ASN1ObjectIdentifier curveOid, byte[] encoded)
    throws BadCertTemplateException {
  Args.notNull(curveOid, "curveOid");
  Args.notNull(encoded, "encoded");
  Args.positive(encoded.length, "encoded.length");

  Integer expectedLength = ecCurveFieldSizes.get(curveOid);
  if (expectedLength == null) {
    X9ECParameters ecP = ECUtil.getNamedCurveByOid(curveOid);
    ECCurve curve = ecP.getCurve();
    expectedLength = (curve.getFieldSize() + 7) / 8;
    ecCurveFieldSizes.put(curveOid, expectedLength);
  }

  switch (encoded[0]) {
    case 0x02: // compressed
    case 0x03: // compressed
      if (encoded.length != (expectedLength + 1)) {
        throw new BadCertTemplateException("incorrect length for compressed encoding");
      }
      break;
    case 0x04: // uncompressed
    case 0x06: // hybrid
    case 0x07: // hybrid
      if (encoded.length != (2 * expectedLength + 1)) {
        throw new BadCertTemplateException("incorrect length for uncompressed/hybrid encoding");
      }
      break;
    default:
      throw new BadCertTemplateException(
          String.format("invalid point encoding 0x%02x", encoded[0]));
  }
}
 
Example #11
Source File: ECAssistant.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static ECDomainParameters ecDomainParametersFrom(X9ECParameters x9ECParameters) {
    return new ECDomainParameters(
            x9ECParameters.getCurve(),
            x9ECParameters.getG(),
            x9ECParameters.getN(),
            x9ECParameters.getH(),
            x9ECParameters.getSeed());
}
 
Example #12
Source File: ECPublicKeyImportCompact.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public Optional<ECPublicKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);

    return ECKeyFactories.publicKeyFactory()
            .createECPublicKey(x, y, curveName);
}
 
Example #13
Source File: ECCurvePoint.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static Optional<ECCurvePoint> create(BigInteger d, String curveName) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    ECPoint Q = new FixedPointCombMultiplier().multiply(x9ECParameters.getG(), d).normalize();

    ECCurvePoint point = new ECCurvePoint(Q, curveName, x9ECParameters);
    return Optional.of(point);
}
 
Example #14
Source File: ECCurvePoint.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static Optional<ECCurvePoint> create(BigInteger x, BigInteger y, String curveName) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    ECPoint Q = x9ECParameters.getCurve()
            .createPoint(x, y);

    if (!Q.isValid()) {
        logger.warn("-- create() - bad Q: {} curve: {}", Q, curveName);
        return Optional.empty();
    }

    ECCurvePoint point = new ECCurvePoint(Q, curveName, x9ECParameters);
    return Optional.of(point);
}
 
Example #15
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 #16
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static boolean verify(byte[] pub, byte[] dataForSigning,
		BigInteger[] rs) throws Exception {
	ECDSASigner signer = new ECDSASigner();
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	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 #17
Source File: NamedCurve.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * UAF_ALG_SIGN_SECP256R1_ECDSA_SHA256_RAW 0x01 An ECDSA signature on the
 * NIST secp256r1 curve which MUST have raw R and S buffers, encoded in
 * big-endian order. I.e. [R (32 bytes), S (32 bytes)]
 * 
 * @param priv
 *            - Private key
 * @param input
 *            - Data to sign
 * @return BigInteger[] - [R,S]
 */
public static BigInteger[] signAndFromatToRS(PrivateKey priv, byte[] input) {
	X9ECParameters params = SECNamedCurves.getByName("secp256r1");
	ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(),
			params.getG(), params.getN(), params.getH());
	if (priv == null)
		throw new IllegalStateException(
				"This ECKey does not have the private key necessary for signing.");
	ECDSASigner signer = new ECDSASigner();
	ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
			((ECPrivateKey) priv).getS(), ecParams);
	signer.init(true, privKey);
	BigInteger[] sigs = signer.generateSignature(input);
	return sigs;
}
 
Example #18
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 #19
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Sign data with the specified elliptic curve private key.
 *
 * @param privateKey elliptic curve private key.
 * @param data       data to sign
 * @return the signed data.
 * @throws CryptoException
 */
private byte[] ecdsaSignToBytes(ECPrivateKey privateKey, byte[] data) throws CryptoException {
    if (data == null) {
        throw new CryptoException("Data that to be signed is null.");
    }
    if (data.length == 0) {
        throw new CryptoException("Data to be signed was empty.");
    }

    try {
        X9ECParameters params = ECNamedCurveTable.getByName(curveName);
        BigInteger curveN = params.getN();

        Signature sig = SECURITY_PROVIDER == null ? Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM) :
                Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM, SECURITY_PROVIDER);
        sig.initSign(privateKey);
        sig.update(data);
        byte[] signature = sig.sign();

        BigInteger[] sigs = decodeECDSASignature(signature);

        sigs = preventMalleability(sigs, curveN);

        try (ByteArrayOutputStream s = new ByteArrayOutputStream()) {

            DERSequenceGenerator seq = new DERSequenceGenerator(s);
            seq.addObject(new ASN1Integer(sigs[0]));
            seq.addObject(new ASN1Integer(sigs[1]));
            seq.close();
            return s.toByteArray();
        }

    } catch (Exception e) {
        throw new CryptoException("Could not sign the message using private key", e);
    }

}
 
Example #20
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Security Level determines the elliptic curve used in key generation
 *
 * @param securityLevel currently 256 or 384
 * @throws InvalidArgumentException
 */
void setSecurityLevel(final int securityLevel) throws InvalidArgumentException {
    logger.trace(format("setSecurityLevel to %d", securityLevel));

    if (securityCurveMapping.isEmpty()) {
        throw new InvalidArgumentException("Security curve mapping has no entries.");
    }

    if (!securityCurveMapping.containsKey(securityLevel)) {
        StringBuilder sb = new StringBuilder();
        String sp = "";
        for (int x : securityCurveMapping.keySet()) {
            sb.append(sp).append(x);

            sp = ", ";

        }
        throw new InvalidArgumentException(format("Illegal security level: %d. Valid values are: %s", securityLevel, sb.toString()));
    }

    String lcurveName = securityCurveMapping.get(securityLevel);

    logger.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName));

    X9ECParameters params = ECNamedCurveTable.getByName(lcurveName);
    //Check if can match curve name to requested strength.
    if (params == null) {

        InvalidArgumentException invalidArgumentException = new InvalidArgumentException(
                format("Curve %s defined for security strength %d was not found.", curveName, securityLevel));

        logger.error(invalidArgumentException);
        throw invalidArgumentException;

    }

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

	ECPublicKeySpec publicKey = new ECPublicKeySpec(ecParameterSpec.getCurve().decodePoint(data), ecParameterSpec);
	KeyFactory kf = KeyFactory.getInstance("ECDH", "BC");
	return (ECPublicKey) kf.generatePublic(publicKey);
}
 
Example #22
Source File: ECCurvePoint.java    From InflatableDonkey with MIT License 4 votes vote down vote up
private ECCurvePoint(Object lock, ECPoint Q, String curveName, X9ECParameters x9ECParameters) {
    this.lock = Objects.requireNonNull(lock, "lock");
    this.Q = Objects.requireNonNull(Q.normalize(), "Q");
    this.curveName = Objects.requireNonNull(curveName, "curveName");
    this.x9ECParameters = Objects.requireNonNull(x9ECParameters, "x9ECParameters");
}
 
Example #23
Source File: ECCurvePoint.java    From InflatableDonkey with MIT License 4 votes vote down vote up
private ECCurvePoint(ECPoint Q, String curveName, X9ECParameters x9ECParameters) {
    this(new Object(), Q, curveName, x9ECParameters);
}
 
Example #24
Source File: ECCurvePoint.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public X9ECParameters x9ECParameters() {
    return ECAssistant.x9ECParameters(curveName);
}
 
Example #25
Source File: ECAssistant.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public static int fieldLength(X9ECParameters x9ECParameters) {
    return fieldLength(x9ECParameters.getCurve());
}
 
Example #26
Source File: EthereumUtil.java    From hadoopcryptoledger with Apache License 2.0 4 votes vote down vote up
/**
 * Calculates the sent address of an EthereumTransaction. Note this can be a costly operation to calculate. . This requires that you have Bouncy castle as a dependency in your project
 *
 *
 * @param eTrans transaction
 * @param chainId chain identifier (e.g. 1 main net)
 * @return sent address as byte array
 */
public static byte[] getSendAddress(EthereumTransaction eTrans, int chainId) {
	// init, maybe we move this out to save time
	X9ECParameters params = SECNamedCurves.getByName("secp256k1");
	ECDomainParameters CURVE=new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());	 // needed for getSentAddress

 
    byte[] transactionHash;

    if ((eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC) || (eTrans.getSig_v()[0]==chainId*2+EthereumUtil.CHAIN_ID_INC+1)) {  // transaction hash with dummy signature data
    	 transactionHash = EthereumUtil.getTransactionHashWithDummySignatureEIP155(eTrans);
    } else {  // transaction hash without signature data
	 transactionHash = EthereumUtil.getTransactionHashWithoutSignature(eTrans);
    }
  // signature to address
	BigInteger bR = new BigInteger(1,eTrans.getSig_r());
	BigInteger bS = new BigInteger(1,eTrans.getSig_s());
  // calculate v for signature
	byte v =(byte) (eTrans.getSig_v()[0]);
	if (!((v == EthereumUtil.LOWER_REAL_V) || (v== (LOWER_REAL_V+1)))) {
		byte vReal = EthereumUtil.LOWER_REAL_V;
		if (((int)v%2 == 0)) {
			v = (byte) (vReal+0x01);
		} else {
			v = vReal;
		}
	}


	// the following lines are inspired from ECKey.java of EthereumJ, but adapted to the hadoopcryptoledger context
	if (v < 27 || v > 34) {
		LOG.error("Header out of Range:  "+v);
		throw new RuntimeException("Header out of range "+v);
	}
	if (v>=31) {

		v -=4;
	}
	int receiverId = v - 27;
	BigInteger n = CURVE.getN();
    BigInteger i = BigInteger.valueOf((long) receiverId / 2);
    BigInteger x = bR.add(i.multiply(n));
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ();
    if (x.compareTo(prime) >= 0) {
        return null;
     }
    // decompress Key
    X9IntegerConverter x9 = new X9IntegerConverter();
    byte[] compEnc = x9.integerToBytes(x, 1 + x9.getByteLength(CURVE.getCurve()));
    boolean yBit=(receiverId & 1) == 1;
    compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
    ECPoint R =  CURVE.getCurve().decodePoint(compEnc);
    if (!R.multiply(n).isInfinity()) {
    		return null;
    }
    BigInteger e = new BigInteger(1,transactionHash);
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = bR.modInverse(n);
    BigInteger srInv = rInv.multiply(bS).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
    byte[] pubKey=q.getEncoded(false);
    // now we need to convert the public key into an ethereum send address which is the last 20 bytes of 32 byte KECCAK-256 Hash of the key.
	Keccak.Digest256 digest256 = new Keccak.Digest256();
	digest256.update(pubKey,1,pubKey.length-1);
	byte[] kcck = digest256.digest();
    return Arrays.copyOfRange(kcck,12,kcck.length);
}
 
Example #27
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 2 votes vote down vote up
/**
 * copy from BC
 *
 * @param genSpec
 * @return
 */
public static X9ECParameters getDomainParametersFromGenSpec(ECGenParameterSpec genSpec) {
    return getDomainParametersFromName(genSpec.getName());
}
 
Example #28
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 2 votes vote down vote up
/**
 * copy from BC
 *
 * @param genSpec
 * @return
 */
public static X9ECParameters getDomainParametersFromGenSpec(ECGenParameterSpec genSpec) {
    return getDomainParametersFromName(genSpec.getName());
}