List of usage examples for org.bouncycastle.crypto.params ECPrivateKeyParameters ECPrivateKeyParameters
public ECPrivateKeyParameters(BigInteger d, ECDomainParameters parameters)
From source file:card.CardClient.java
License:Open Source License
/** * Get an attribute from the card/*from w w w .ja v a 2 s. c o m*/ * * @param i Index of the attribute. * @return Blinded public key, blinded attribute signature and the attribute */ public BigInteger[] getAttribute(byte id, ECPoint nonce) { BigInteger[] result = new BigInteger[3]; int i = 0; while (i < attribute.length && attribute_id[i] != id) i++; if (i >= attribute.length || attribute_id[i] != id) { return null; } result[ATTRIBUTE] = attribute[i]; // generate a blinding factor b blinder = (ECPrivateKey) keyGen.generateKeyPair().getPrivate(); // blind public key, attribute signature and signed nonce try { ECDHBasicAgreement agreement = new ECDHBasicAgreement(); agreement.init(new ECPrivateKeyParameters(blinder.getD(), ecDom)); result[BLINDED_KEY] = agreement .calculateAgreement(new ECPublicKeyParameters(((ECPublicKey) keys.getPublic()).getQ(), ecDom)); result[BLINDED_SIGNATURE] = agreement .calculateAgreement(new ECPublicKeyParameters(signature[i], ecDom)); result[SIGNED_NONCE] = agreement.calculateAgreement( new ECPublicKeyParameters(nonce.multiply(((ECPrivateKey) keys.getPrivate()).getD()), ecDom)); } catch (Exception e) { e.printStackTrace(); } // return blinded public key, blinded attribute signature, blinded signed nonce, attribute return result; }
From source file:co.rsk.peg.BridgeSupportTest.java
License:Open Source License
/** * Helper method to test addSignature() with a valid federatorPublicKey parameter and both valid/invalid signatures * @param privateKeysToSignWith keys used to sign the tx. Federator key when we want to produce a valid signature, a random key when we want to produce an invalid signature * @param numberOfInputsToSign There is just 1 input. 1 when testing the happy case, other values to test attacks/bugs. * @param signatureCanonical Signature should be canonical. true when testing the happy case, false to test attacks/bugs. * @param signTwice Sign again with the same key * @param expectedResult "InvalidParameters", "PartiallySigned" or "FullySigned" *///from w ww . j a va2 s . c om private void addSignatureFromValidFederator(List<BtcECKey> privateKeysToSignWith, int numberOfInputsToSign, boolean signatureCanonical, boolean signTwice, String expectedResult) throws Exception { // Federation is the genesis federation ATM Federation federation = bridgeConstants.getGenesisFederation(); Repository repository = createRepositoryImpl(config); final Keccak256 keccak256 = PegTestUtils.createHash3(); Repository track = repository.startTracking(); BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), bridgeStorageConfigurationAtHeightZero); BtcTransaction prevTx = new BtcTransaction(btcParams); TransactionOutput prevOut = new TransactionOutput(btcParams, prevTx, Coin.FIFTY_COINS, federation.getAddress()); prevTx.addOutput(prevOut); BtcTransaction t = new BtcTransaction(btcParams); TransactionOutput output = new TransactionOutput(btcParams, t, Coin.COIN, new BtcECKey().toAddress(btcParams)); t.addOutput(output); t.addInput(prevOut).setScriptSig(PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(federation)); provider.getRskTxsWaitingForSignatures().put(keccak256, t); provider.save(); track.commit(); track = repository.startTracking(); List<LogInfo> logs = new ArrayList<>(); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(bridgeConstants, logs); BridgeSupport bridgeSupport = new BridgeSupport(config, track, eventLogger, contractAddress, mock(Block.class)); Script inputScript = t.getInputs().get(0).getScriptSig(); List<ScriptChunk> chunks = inputScript.getChunks(); byte[] program = chunks.get(chunks.size() - 1).data; Script redeemScript = new Script(program); Sha256Hash sighash = t.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); BtcECKey.ECDSASignature sig = privateKeysToSignWith.get(0).sign(sighash); if (!signatureCanonical) { sig = new BtcECKey.ECDSASignature(sig.r, BtcECKey.CURVE.getN().subtract(sig.s)); } byte[] derEncodedSig = sig.encodeToDER(); List derEncodedSigs = new ArrayList(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs.add(derEncodedSig); } bridgeSupport.addSignature(findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)), derEncodedSigs, keccak256.getBytes()); if (signTwice) { // Create another valid signature with the same private key ECDSASigner signer = new ECDSASigner(); X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); ECDomainParameters CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(), CURVE_PARAMS.getN(), CURVE_PARAMS.getH()); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(), CURVE); signer.init(true, privKey); BigInteger[] components = signer.generateSignature(sighash.getBytes()); BtcECKey.ECDSASignature sig2 = new BtcECKey.ECDSASignature(components[0], components[1]) .toCanonicalised(); bridgeSupport.addSignature( findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)), Lists.newArrayList(sig2.encodeToDER()), keccak256.getBytes()); } if (privateKeysToSignWith.size() > 1) { BtcECKey.ECDSASignature sig2 = privateKeysToSignWith.get(1).sign(sighash); byte[] derEncodedSig2 = sig2.encodeToDER(); List derEncodedSigs2 = new ArrayList(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs2.add(derEncodedSig2); } bridgeSupport.addSignature( findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(1)), derEncodedSigs2, keccak256.getBytes()); } bridgeSupport.save(); track.commit(); provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), bridgeStorageConfigurationAtHeightZero); if ("FullySigned".equals(expectedResult)) { Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertThat(logs, is(not(empty()))); Assert.assertThat(logs, hasSize(3)); LogInfo releaseTxEvent = logs.get(2); Assert.assertThat(releaseTxEvent.getTopics(), hasSize(1)); Assert.assertThat(releaseTxEvent.getTopics(), hasItem(Bridge.RELEASE_BTC_TOPIC)); BtcTransaction releaseTx = new BtcTransaction(bridgeConstants.getBtcParams(), ((RLPList) RLP.decode2(releaseTxEvent.getData()).get(0)).get(1).getRLPData()); Script retrievedScriptSig = releaseTx.getInput(0).getScriptSig(); Assert.assertEquals(4, retrievedScriptSig.getChunks().size()); Assert.assertEquals(true, retrievedScriptSig.getChunks().get(1).data.length > 0); Assert.assertEquals(true, retrievedScriptSig.getChunks().get(2).data.length > 0); } else { Script retrievedScriptSig = provider.getRskTxsWaitingForSignatures().get(keccak256).getInput(0) .getScriptSig(); Assert.assertEquals(4, retrievedScriptSig.getChunks().size()); boolean expectSignatureToBePersisted = false; // for "InvalidParameters" if ("PartiallySigned".equals(expectedResult)) { expectSignatureToBePersisted = true; } Assert.assertEquals(expectSignatureToBePersisted, retrievedScriptSig.getChunks().get(1).data.length > 0); Assert.assertEquals(false, retrievedScriptSig.getChunks().get(2).data.length > 0); } }
From source file:com.bitsofproof.supernode.api.ECKeyPair.java
License:Apache License
@Override public byte[] sign(byte[] hash) throws ValidationException { if (priv == null) { throw new ValidationException("Need private key to sign"); }/* w w w.ja v a 2 s. c om*/ ECDSASigner signer = new ECDSASigner(); signer.init(true, new ECPrivateKeyParameters(priv, domain)); BigInteger[] signature = signer.generateSignature(hash); ByteArrayOutputStream s = new ByteArrayOutputStream(); try { DERSequenceGenerator seq = new DERSequenceGenerator(s); seq.addObject(new DERInteger(signature[0])); seq.addObject(new DERInteger(signature[1])); seq.close(); return s.toByteArray(); } catch (IOException e) { } return null; }
From source file:com.cryptolib.CryptoObject.java
License:Open Source License
/** * Performs ECDH/* w w w .jav a 2s .c o m*/ */ public void createSharedEncKey(ECPublicKey key) throws CryptoSocketException { try { X9ECParameters ecP = CustomNamedCurves.getByName(curve); ECDomainParameters ecdp = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH()); ECPublicKeyParameters ecpkp = new ECPublicKeyParameters(key.getQ(), ecdp); BCECPrivateKey sk = (BCECPrivateKey) this.encKeypair.getPrivate(); ECPrivateKeyParameters ecskp = new ECPrivateKeyParameters(sk.getD(), ecdp); ECDHCBasicAgreement ba = new ECDHCBasicAgreement(); ba.init(ecskp); byte[] byteSharedSecret = ba.calculateAgreement(ecpkp).toByteArray(); byte[] byteSharedSecretSecond = new byte[byteSharedSecret.length / 2]; byte[] byteSharedSecretFirst = new byte[byteSharedSecret.length / 2]; System.arraycopy(byteSharedSecret, 0, byteSharedSecretSecond, 0, byteSharedSecretSecond.length); System.arraycopy(byteSharedSecret, byteSharedSecretSecond.length, byteSharedSecretFirst, 0, byteSharedSecretFirst.length); this.sharedSecretFirst = new SecretKeySpec(byteSharedSecretFirst, "AES"); this.sharedSecretSecond = new SecretKeySpec(byteSharedSecretSecond, "AES"); this.has_symmetric_key = true; this.enc = Cipher.getInstance("AES/GCM/NoPadding"); this.dec = Cipher.getInstance("AES/GCM/NoPadding"); } catch (IllegalStateException is) { throw new CryptoSocketException("unable to create shared encryption key, wrong state!"); } catch (NoSuchAlgorithmException nsa) { throw new CryptoSocketException("Encryption algorithm not found!"); } catch (NoSuchPaddingException nsp) { throw new CryptoSocketException("Invalid padding algorithm!"); } }
From source file:com.DSC.crypto.ECGKeyUtil.java
License:Open Source License
/** * decodePriKey A function which takes an ECC private key parameter object and * returns an ECPrivateKeyParameters object for the private key D BigInteger * value./*from w w w . j ava 2s . c o m*/ * * @param param The Elliptic Curve key parameter which contains the curve * specifications and domain parameters * @param priKey a byte array of the private key D BigInteger value * @return an ECPrivateKeyParameters object for the private key D BigInteger value */ static public ECPrivateKeyParameters decodePriKey(byte[] encodedPriKey) { return new ECPrivateKeyParameters(new BigInteger(encodedPriKey), // D param.getECDomainParam()); }
From source file:com.facebook.delegatedrecovery.RecoveryToken.java
License:Open Source License
private byte[] getSignature(final byte[] rawArray, final ECPrivateKey privateKey) throws IOException { if (this.signature != null) { throw new IllegalStateException("This token already has a signature."); }/*from w ww .j a va2 s. c o m*/ final BigInteger privatePoint = privateKey.getS(); final SHA256Digest digest = new SHA256Digest(); final byte[] hash = new byte[digest.getByteLength()]; digest.update(rawArray, 0, rawArray.length); digest.doFinal(hash, 0); final ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); signer.init(true, new ECPrivateKeyParameters(privatePoint, DelegatedRecoveryUtils.P256_DOMAIN_PARAMS)); final BigInteger[] signature = signer.generateSignature(hash); final ByteArrayOutputStream s = new ByteArrayOutputStream(); final DERSequenceGenerator seq = new DERSequenceGenerator(s); seq.addObject(new ASN1Integer(signature[0])); seq.addObject(new ASN1Integer(signature[1])); seq.close(); return s.toByteArray(); }
From source file:com.google.bitcoin.core.ECKey.java
License:Apache License
/** * Signs the given hash and returns the R and S components as BigIntegers. In the Bitcoin protocol, they are * usually encoded using DER format, so you want {@link com.google.bitcoin.core.ECKey.ECDSASignature#encodeToDER()} * instead. However sometimes the independent components can be useful, for instance, if you're doing to do further * EC maths on them.//w w w.ja va 2 s.co m * * @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required. * @throws KeyCrypterException if this ECKey doesn't have a private part. */ public ECDSASignature sign(Sha256Hash input, @Nullable KeyParameter aesKey) throws KeyCrypterException { if (FAKE_SIGNATURES) return TransactionSignature.dummy(); // The private key bytes to use for signing. BigInteger privateKeyForSigning; if (isEncrypted()) { // The private key needs decrypting before use. if (aesKey == null) { throw new KeyCrypterException("This ECKey is encrypted but no decryption key has been supplied."); } if (keyCrypter == null) { throw new KeyCrypterException("There is no KeyCrypter to decrypt the private key for signing."); } privateKeyForSigning = new BigInteger(1, keyCrypter.decrypt(encryptedPrivateKey, aesKey)); // Check encryption was correct. if (!Arrays.equals(pub, publicKeyFromPrivate(privateKeyForSigning, isCompressed()))) throw new KeyCrypterException("Could not decrypt bytes"); } else { // No decryption of private key required. if (priv == null) { throw new KeyCrypterException("This ECKey does not have the private key necessary for signing."); } else { privateKeyForSigning = priv; } } ECDSASigner signer = new ECDSASigner(); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE); signer.init(true, privKey); BigInteger[] components = signer.generateSignature(input.getBytes()); final ECDSASignature signature = new ECDSASignature(components[0], components[1]); signature.ensureCanonical(); return signature; }
From source file:com.licel.jcardsim.crypto.ECPrivateKeyImpl.java
License:Apache License
/** * Get <code>ECPrivateKeyParameters</code> * @return parameters for use with BouncyCastle API * @see ECPrivateKeyParameters//from ww w . j av a 2 s .c o m */ public CipherParameters getParameters() { if (!isInitialized()) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } return new ECPrivateKeyParameters(s.getBigInteger(), getDomainParameters()); }
From source file:common.crypto.bouncycastle.CEcdsaSignerBC.java
License:Open Source License
@Override public EcdsaSignature sign(byte[] byaMessage, BigInteger nSecretKey) { ECKeyParameters privParameters = new ECPrivateKeyParameters(nSecretKey, m_eccParameter); m_signer.init(true, privParameters); byte[] byaHashedMessage = m_shaHash.digest(byaMessage); BigInteger[] sig = m_signer.generateSignature(byaHashedMessage); return new EcdsaSignature(sig); }
From source file:COSE.ECPrivateKey.java
public ECPrivateKey(OneKey oneKey) throws CoseException, IOException { X9ECParameters p = oneKey.GetCurve(); org.bouncycastle.math.ec.ECPoint pubPoint; ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); if (oneKey.get(KeyKeys.EC2_Y).getType() == CBORType.Boolean) { byte[] X = oneKey.get(KeyKeys.EC2_X.AsCBOR()).GetByteString(); byte[] rgb = new byte[X.length + 1]; System.arraycopy(X, 0, rgb, 1, X.length); rgb[0] = (byte) (2 + (oneKey.get(KeyKeys.EC2_Y).AsBoolean() ? 1 : 0)); pubPoint = p.getCurve().decodePoint(rgb); point = new ECPoint(point.getAffineX(), point.getAffineY()); } else {/* w w w . j a v a 2 s . c o m*/ point = new ECPoint(new BigInteger(1, oneKey.get(KeyKeys.EC2_X).GetByteString()), new BigInteger(1, oneKey.get(KeyKeys.EC2_Y).GetByteString())); pubPoint = p.getCurve().createPoint(new BigInteger(1, oneKey.get(KeyKeys.EC2_X).GetByteString()), new BigInteger(1, oneKey.get(KeyKeys.EC2_Y).GetByteString())); } ECPublicKeyParameters pub = new ECPublicKeyParameters(pubPoint, parameters); ECPrivateKeyParameters priv = new ECPrivateKeyParameters( new BigInteger(1, oneKey.get(KeyKeys.EC2_D.AsCBOR()).GetByteString()), parameters); /* switch (AlgorithmID.FromCBOR(oneKey.get(KeyKeys.Algorithm))) { case ECDH_ES_HKDF_256: case ECDH_ES_HKDF_512: case ECDH_SS_HKDF_256: case ECDH_SS_HKDF_512: case ECDH_ES_HKDF_256_AES_KW_128: case ECDH_ES_HKDF_256_AES_KW_192: case ECDH_ES_HKDF_256_AES_KW_256: case ECDH_SS_HKDF_256_AES_KW_128: case ECDH_SS_HKDF_256_AES_KW_192: case ECDH_SS_HKDF_256_AES_KW_256: algorithm = "ECDH"; break; case ECDSA_256: algorithm = "SHA256withECDSA"; break; case ECDSA_384: algorithm = "SHA384withECDSA"; break; case ECDSA_512: algorithm = "SHA512withECDSA"; break; default: throw new CoseException("No algorithm specified"); } */ algorithm = "EC"; CBORObject curve = oneKey.get(KeyKeys.EC2_Curve); int keySize; ASN1ObjectIdentifier curveOID; if (curve.equals(KeyKeys.EC2_P256)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp256r1; keySize = 256; } else if (curve.equals(KeyKeys.EC2_P384)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp384r1; keySize = 384; } else if (curve.equals(KeyKeys.EC2_P521)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp521r1; keySize = 521; } else { throw new CoseException("Unrecognized Curve"); } privateKey = new BigInteger(1, oneKey.get(KeyKeys.EC2_D).GetByteString()); ECField field = new ECFieldFp(p.getCurve().getField().getCharacteristic()); EllipticCurve crv = new EllipticCurve(field, p.getCurve().getA().toBigInteger(), p.getCurve().getB().toBigInteger()); ECPoint pt = new ECPoint(p.getG().getRawXCoord().toBigInteger(), p.getG().getRawYCoord().toBigInteger()); ecParameterSpec = new ECParameterSpec(crv, pt, p.getN(), p.getH().intValue()); AlgorithmIdentifier alg = new AlgorithmIdentifier(org.bouncycastle.asn1.x9.X9Curve.id_ecPublicKey, curveOID); org.bouncycastle.asn1.sec.ECPrivateKey asnPrivate = new org.bouncycastle.asn1.sec.ECPrivateKey(keySize, privateKey); byte[] x = asnPrivate.getEncoded(); PrivateKeyInfo asnPrivateX = new PrivateKeyInfo(alg, asnPrivate); encodedKey = asnPrivateX.getEncoded(); }