List of usage examples for org.bouncycastle.math.ec ECPoint getEncoded
public byte[] getEncoded(boolean compressed)
From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java
License:Apache License
/** * Generate reconstruction data for an implicit certificate In the terminology of sec4, * ephemeralPublicKey is referenced as Ru * * @param identifyingInfo the identity portion of the implicit certificate * @param ephemeralPublicKey the requesters ephemeral public key * @param issuerPrivateKey the issuers private key * * @return reconstruction data associated with the implicit certificate * * @throws NoSuchAlgorithmException From Bouncy Castle * @throws InvalidAlgorithmParameterException From Bouncy Castle * @throws NoSuchProviderException From Bouncy Castle * @throws IOException//from w w w.j a v a 2s . c o m */ public KeyReconstructionData genReconstructionData(byte[] identifyingInfo, PublicKey ephemeralPublicKey, PrivateKey issuerPrivateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, IOException { // Reconstruction point, in point and byte format ECPoint p; byte[] reconstructionPoint; // CA's ephemeral key pair (k, kG) BCECPublicKey caEphemeralPublicKey; BCECPrivateKey caEphemeralPrivateKey; BigInteger n = curveParameters.getN(); // get the order of the curve group BigInteger r; // private key recovery data and CA ephemeral private key, respectively. BigInteger e; // Integer representation of H(Certu) BigInteger dCa = ((BCECPrivateKey) issuerPrivateKey).getD(); // Private key (point multiplier) // of the issuer. ECPoint infinity = curveParameters.getCurve().getInfinity(); // The identity point. do { // create ephemeral key pair (k, kG) KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME); keyGen.initialize(curveParameters, random); KeyPair caEphemeralKeyPair = keyGen.generateKeyPair(); caEphemeralPrivateKey = (BCECPrivateKey) caEphemeralKeyPair.getPrivate(); caEphemeralPublicKey = (BCECPublicKey) caEphemeralKeyPair.getPublic(); // Compute Pu = Ru + kG // this is the reconstruction point p = ((BCECPublicKey) ephemeralPublicKey).getQ().add(caEphemeralPublicKey.getQ()); reconstructionPoint = p.getEncoded(true); // Update the digest with the implicit certificate Certu for (byte b : identifyingInfo) { digest.update(b); } // Update digest with reconstruction point data. for (byte b : reconstructionPoint) { digest.update(b); } // hash the implicit certificate Certu and compute the integer e from H(Certu) e = calculateE(n, digest.digest()).mod(n); // from sec4 S3.4 } while (p.multiply(e).add(curveParameters.getG().multiply(dCa)).equals(infinity)); // compute r = ek + dCA (mod n) r = e.multiply(caEphemeralPrivateKey.getD()).add(dCa).mod(n); return new KeyReconstructionData(reconstructionPoint, integerToOctetString(r, n)); }
From source file:com.bitsofproof.supernode.common.ExtendedKey.java
License:Apache License
private ExtendedKey generateKey(int sequence) throws ValidationException { try {//from w w w . j av a 2 s . c o m if ((sequence & 0x80000000) != 0 && master.getPrivate() == null) { throw new ValidationException("need private key for private generation"); } Mac mac = Mac.getInstance("HmacSHA512", "BC"); SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512"); mac.init(key); byte[] extended; byte[] pub = master.getPublic(); if ((sequence & 0x80000000) == 0) { extended = new byte[pub.length + 4]; System.arraycopy(pub, 0, extended, 0, pub.length); extended[pub.length] = (byte) ((sequence >>> 24) & 0xff); extended[pub.length + 1] = (byte) ((sequence >>> 16) & 0xff); extended[pub.length + 2] = (byte) ((sequence >>> 8) & 0xff); extended[pub.length + 3] = (byte) (sequence & 0xff); } else { byte[] priv = master.getPrivate(); extended = new byte[priv.length + 5]; System.arraycopy(priv, 0, extended, 1, priv.length); extended[priv.length + 1] = (byte) ((sequence >>> 24) & 0xff); extended[priv.length + 2] = (byte) ((sequence >>> 16) & 0xff); extended[priv.length + 3] = (byte) ((sequence >>> 8) & 0xff); extended[priv.length + 4] = (byte) (sequence & 0xff); } byte[] lr = mac.doFinal(extended); byte[] l = Arrays.copyOfRange(lr, 0, 32); byte[] r = Arrays.copyOfRange(lr, 32, 64); BigInteger m = new BigInteger(1, l); if (m.compareTo(curve.getN()) >= 0 || m.compareTo(BigInteger.ZERO) == 0) { throw new ValidationException("This is rather unlikely, but it did just happen"); } if (master.getPrivate() != null) { BigInteger k = m.add(new BigInteger(1, master.getPrivate())).mod(curve.getN()); if (k.compareTo(BigInteger.ZERO) == 0) { throw new ValidationException("This is rather unlikely, but it did just happen"); } return new ExtendedKey(new ECKeyPair(k, true), r, depth, parent, sequence); } else { ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub)); if (q.isInfinity()) { throw new ValidationException("This is rather unlikely, but it did just happen"); } pub = q.getEncoded(true); return new ExtendedKey(new ECPublicKey(pub, true), r, depth, parent, sequence); } } catch (NoSuchAlgorithmException e) { throw new ValidationException(e); } catch (NoSuchProviderException e) { throw new ValidationException(e); } catch (InvalidKeyException e) { throw new ValidationException(e); } }
From source file:org.cryptoworkshop.ximix.common.crypto.ECDecryptionProof.java
License:Apache License
private void addIn(SHA256Digest sha256, ECPoint point) { byte[] enc = point.getEncoded(true); sha256.update(enc, 0, enc.length); }
From source file:org.ethereum.crypto.ECIESCoder.java
License:Open Source License
public static byte[] encrypt(ECPoint toPub, byte[] plaintext, byte[] macData) { ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random); eGen.init(gParam);//from www .j a v a 2 s.c o m byte[] iv = new byte[KEY_SIZE / 8]; new SecureRandom().nextBytes(iv); AsymmetricCipherKeyPair ephemPair = eGen.generateKeyPair(); BigInteger prv = ((ECPrivateKeyParameters) ephemPair.getPrivate()).getD(); ECPoint pub = ((ECPublicKeyParameters) ephemPair.getPublic()).getQ(); EthereumIESEngine iesEngine = makeIESEngine(true, toPub, prv, iv); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, random); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keygenParams); ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ECKey.CURVE, random)); byte[] cipher; try { cipher = iesEngine.processBlock(plaintext, 0, plaintext.length, macData); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(pub.getEncoded(false)); bos.write(iv); bos.write(cipher); return bos.toByteArray(); } catch (InvalidCipherTextException e) { throw Throwables.propagate(e); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:org.ethereum.crypto.ECIESTest.java
License:Open Source License
public static byte[] encrypt(ECPoint toPub, byte[] plaintext) throws InvalidCipherTextException, IOException { ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(curve, random); eGen.init(gParam);/*from www . j a v a2 s .c om*/ byte[] IV = new byte[KEY_SIZE / 8]; new SecureRandom().nextBytes(IV); AsymmetricCipherKeyPair ephemPair = eGen.generateKeyPair(); BigInteger prv = ((ECPrivateKeyParameters) ephemPair.getPrivate()).getD(); ECPoint pub = ((ECPublicKeyParameters) ephemPair.getPublic()).getQ(); EthereumIESEngine iesEngine = makeIESEngine(true, toPub, prv, IV); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(curve, random); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keygenParams); ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ECKey.CURVE, random)); byte[] cipher = iesEngine.processBlock(plaintext, 0, plaintext.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(pub.getEncoded(false)); bos.write(IV); bos.write(cipher); return bos.toByteArray(); }
From source file:org.ethereum.crypto.ECKey.java
License:Open Source License
/** * Utility for compressing an elliptic curve point. Returns the same point if it's already compressed. * See the ECKey class docs for a discussion of point compression. * * @param uncompressed -//ww w. j a v a 2s.com * * @return - */ public static ECPoint compressPoint(ECPoint uncompressed) { return CURVE.getCurve().decodePoint(uncompressed.getEncoded(true)); }
From source file:org.ethereum.crypto.ECKey.java
License:Open Source License
/** * Utility for decompressing an elliptic curve point. Returns the same point if it's already compressed. * See the ECKey class docs for a discussion of point compression. * * @param compressed -/* www.j a v a 2 s .c o m*/ * * @return - */ public static ECPoint decompressPoint(ECPoint compressed) { return CURVE.getCurve().decodePoint(compressed.getEncoded(false)); }
From source file:org.ethereum.crypto.ECKey.java
License:Open Source License
/** * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, use <tt> * new BigInteger(1, bytes);</tt>/* w w w . j a va 2 s . c o m*/ * * @param privKey - * @param compressed - * @return - */ public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) { ECPoint point = CURVE.getG().multiply(privKey); return point.getEncoded(compressed); }
From source file:org.ethereum.net.rlpx.HandshakeHandler.java
License:Open Source License
private void decodeHandshake(final ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { if (handshake.isInitiator()) { if (frameCodec == null) { byte[] responsePacket = new byte[AuthResponseMessage.getLength() + ECIESCoder.getOverhead()]; if (!buffer.isReadable(responsePacket.length)) { return; }/* w w w. j a v a 2s . co m*/ buffer.readBytes(responsePacket); try { // trying to decode as pre-EIP-8 AuthResponseMessage response = handshake.handleAuthResponse(myKey, initiatePacket, responsePacket); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), response); } catch (Throwable t) { // it must be format defined by EIP-8 then responsePacket = readEIP8Packet(buffer, responsePacket); if (responsePacket == null) { return; } AuthResponseMessageV4 response = handshake.handleAuthResponseV4(myKey, initiatePacket, responsePacket); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), response); } EncryptionHandshake.Secrets secrets = this.handshake.getSecrets(); this.frameCodec = new FrameCodec(secrets); loggerNet.trace("auth exchange done"); channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId), null); } else { loggerWire.debug("MessageCodec: Buffer bytes: {}", buffer.readableBytes()); List<Frame> frames = frameCodec.readFrames(buffer); if (frames == null || frames.isEmpty()) { return; } Frame frame = frames.get(0); byte[] payload = ByteStreams.toByteArray(frame.getStream()); if (frame.getType() == P2pMessageCodes.HELLO.asByte()) { HelloMessage helloMessage = new HelloMessage(payload); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), helloMessage); processHelloMessage(ctx, helloMessage); } else { DisconnectMessage message = new DisconnectMessage(payload); loggerNet.trace("From: \t{} \tRecv: \t{}", channel, message); channel.getNodeStatistics().nodeDisconnectedRemote(message.getReason()); } } } else { loggerWire.debug("Not initiator."); if (frameCodec == null) { loggerWire.debug("FrameCodec == null"); byte[] authInitPacket = new byte[AuthInitiateMessage.getLength() + ECIESCoder.getOverhead()]; if (!buffer.isReadable(authInitPacket.length)) { return; } buffer.readBytes(authInitPacket); this.handshake = new EncryptionHandshake(); byte[] responsePacket; try { // trying to decode as pre-EIP-8 AuthInitiateMessage initiateMessage = handshake.decryptAuthInitiate(authInitPacket, myKey); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), initiateMessage); AuthResponseMessage response = handshake.makeAuthInitiate(initiateMessage, myKey); loggerNet.trace("To: \t{} \tSend: \t{}", ctx.channel().remoteAddress(), response); responsePacket = handshake.encryptAuthResponse(response); } catch (Throwable t) { // it must be format defined by EIP-8 then try { authInitPacket = readEIP8Packet(buffer, authInitPacket); if (authInitPacket == null) { return; } AuthInitiateMessageV4 initiateMessage = handshake.decryptAuthInitiateV4(authInitPacket, myKey); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), initiateMessage); AuthResponseMessageV4 response = handshake.makeAuthInitiateV4(initiateMessage, myKey); loggerNet.trace("To: \t{} \tSend: \t{}", ctx.channel().remoteAddress(), response); responsePacket = handshake.encryptAuthResponseV4(response); } catch (InvalidCipherTextException ce) { loggerNet.warn( "Can't decrypt AuthInitiateMessage from {}. Most likely the remote peer used wrong public key (NodeID) to encrypt message.", ctx.channel().remoteAddress()); return; } } handshake.agreeSecret(authInitPacket, responsePacket); EncryptionHandshake.Secrets secrets = this.handshake.getSecrets(); this.frameCodec = new FrameCodec(secrets); ECPoint remotePubKey = this.handshake.getRemotePublicKey(); byte[] compressed = remotePubKey.getEncoded(false); this.remoteId = new byte[compressed.length - 1]; System.arraycopy(compressed, 1, this.remoteId, 0, this.remoteId.length); channel.setNode(remoteId); final ByteBuf byteBufMsg = ctx.alloc().buffer(responsePacket.length); byteBufMsg.writeBytes(responsePacket); ctx.writeAndFlush(byteBufMsg).sync(); } else { List<Frame> frames = frameCodec.readFrames(buffer); if (frames == null || frames.isEmpty()) { return; } Frame frame = frames.get(0); Message message = new P2pMessageFactory().create((byte) frame.getType(), ByteStreams.toByteArray(frame.getStream())); loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), message); if (frame.getType() == P2pMessageCodes.DISCONNECT.asByte()) { loggerNet.info("Active remote peer disconnected right after handshake."); return; } if (frame.getType() != P2pMessageCodes.HELLO.asByte()) { throw new RuntimeException("The message type is not HELLO or DISCONNECT: " + message); } HelloMessage inboundHelloMessage = (HelloMessage) message; // Secret authentication finish here channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId), inboundHelloMessage); processHelloMessage(ctx, inboundHelloMessage); } } channel.getNodeStatistics().rlpxInHello.add(); }
From source file:org.hyperledger.common.MasterPublicKey.java
License:Apache License
private MasterPublicKey generateKey(int sequence) throws HyperLedgerException { try {/*from ww w . jav a 2s . co m*/ if ((sequence & 0x80000000) != 0) { throw new HyperLedgerException("need private key for hardened generation"); } Mac mac = Mac.getInstance("HmacSHA512", "BC"); SecretKey key = new SecretKeySpec(chainCode, "HmacSHA512"); mac.init(key); byte[] extended; byte[] pub = master.toByteArray(); extended = new byte[pub.length + 4]; System.arraycopy(pub, 0, extended, 0, pub.length); extended[pub.length] = (byte) ((sequence >>> 24) & 0xff); extended[pub.length + 1] = (byte) ((sequence >>> 16) & 0xff); extended[pub.length + 2] = (byte) ((sequence >>> 8) & 0xff); extended[pub.length + 3] = (byte) (sequence & 0xff); byte[] lr = mac.doFinal(extended); byte[] l = Arrays.copyOfRange(lr, 0, 32); byte[] r = Arrays.copyOfRange(lr, 32, 64); BigInteger m = new BigInteger(1, l); if (m.compareTo(curve.getN()) >= 0 || m.compareTo(BigInteger.ZERO) == 0) { throw new HyperLedgerException("This is rather unlikely, but it did just happen"); } ECPoint q = curve.getG().multiply(m).add(curve.getCurve().decodePoint(pub)); if (q.isInfinity()) { throw new HyperLedgerException("This is rather unlikely, but it did just happen"); } pub = q.getEncoded(true); return new MasterPublicKey(new PublicKey(pub, true), r, depth, parent, sequence); } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException e) { throw new HyperLedgerException(e); } }