Java Code Examples for org.bouncycastle.asn1.x9.X9ECParameters#getN()

The following examples show how to use org.bouncycastle.asn1.x9.X9ECParameters#getN() . 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: 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 2
Source File: ECDHExportTest.java    From Encryptor4j with MIT License 6 votes vote down vote up
@Test
public void testExportImport() throws GeneralSecurityException {

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

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

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

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

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

	Assert.assertArrayEquals(ecPublicKey.getEncoded(), importedECPublicKey.getEncoded());
}
 
Example 3
Source File: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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);
}