Search in sources :

Example 1 with InvalidCipherTextException

use of org.spongycastle.crypto.InvalidCipherTextException in project rskj by rsksmart.

the class HandshakeHandler method decodeHandshake.

// consume handshake, producing no resulting message to upper layers
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;
            }
            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);
                isHandshakeDone = true;
                this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, helloMessage);
                recordSuccessfulHandshake(ctx);
            } 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 " + ctx.channel().remoteAddress() + ". Most likely the remote peer used wrong public key (NodeID) to encrypt message.");
                    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);
            isHandshakeDone = true;
            this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, inboundHelloMessage);
            recordSuccessfulHandshake(ctx);
        }
    }
    channel.getNodeStatistics().rlpxInHello.add();
}
Also used : Frame(org.ethereum.net.rlpx.FrameCodec.Frame) InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) HelloMessage(org.ethereum.net.p2p.HelloMessage) DisconnectMessage(org.ethereum.net.p2p.DisconnectMessage) Message(org.ethereum.net.message.Message) HelloMessage(org.ethereum.net.p2p.HelloMessage) DisconnectMessage(org.ethereum.net.p2p.DisconnectMessage) P2pMessageFactory(org.ethereum.net.p2p.P2pMessageFactory) ECPoint(org.spongycastle.math.ec.ECPoint) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with InvalidCipherTextException

use of org.spongycastle.crypto.InvalidCipherTextException in project bitcoin-wallet by bitcoin-wallet.

the class Crypto method encryptRaw.

/**
 * Password based encryption using AES - CBC 256 bits.
 *
 * @param plainBytes
 *            The bytes to encrypt
 * @param password
 *            The password to use for encryption
 * @return SALT_LENGTH bytes of salt followed by the encrypted bytes.
 * @throws IOException
 */
private static byte[] encryptRaw(final byte[] plainTextAsBytes, final char[] password) throws IOException {
    try {
        // Generate salt - each encryption call has a different salt.
        final byte[] salt = new byte[SALT_LENGTH];
        secureRandom.nextBytes(salt);
        final ParametersWithIV key = (ParametersWithIV) getAESPasswordKey(password, salt);
        // The following code uses an AES cipher to encrypt the message.
        final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, key);
        final byte[] encryptedBytes = new byte[cipher.getOutputSize(plainTextAsBytes.length)];
        final int processLen = cipher.processBytes(plainTextAsBytes, 0, plainTextAsBytes.length, encryptedBytes, 0);
        final int doFinalLen = cipher.doFinal(encryptedBytes, processLen);
        // The result bytes are the SALT_LENGTH bytes followed by the encrypted bytes.
        return concat(salt, Arrays.copyOf(encryptedBytes, processLen + doFinalLen));
    } catch (final InvalidCipherTextException | DataLengthException x) {
        throw new IOException("Could not encrypt bytes", x);
    }
}
Also used : ParametersWithIV(org.spongycastle.crypto.params.ParametersWithIV) PaddedBufferedBlockCipher(org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher) InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) BufferedBlockCipher(org.spongycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher) DataLengthException(org.spongycastle.crypto.DataLengthException) CBCBlockCipher(org.spongycastle.crypto.modes.CBCBlockCipher) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) IOException(java.io.IOException)

Example 3 with InvalidCipherTextException

use of org.spongycastle.crypto.InvalidCipherTextException in project libsignal-service-java by signalapp.

the class ProfileCipher method decryptName.

public byte[] decryptName(byte[] input) throws InvalidCiphertextException {
    try {
        if (input.length < 12 + 16 + 1) {
            throw new InvalidCiphertextException("Too short: " + input.length);
        }
        byte[] nonce = new byte[12];
        System.arraycopy(input, 0, nonce, 0, nonce.length);
        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        cipher.init(false, new AEADParameters(new KeyParameter(key), 128, nonce));
        byte[] paddedPlaintextOne = new byte[cipher.getUpdateOutputSize(input.length - 12)];
        cipher.processBytes(input, 12, input.length - 12, paddedPlaintextOne, 0);
        byte[] paddedPlaintextTwo = new byte[cipher.getOutputSize(0)];
        cipher.doFinal(paddedPlaintextTwo, 0);
        byte[] paddedPlaintext = ByteUtil.combine(paddedPlaintextOne, paddedPlaintextTwo);
        int plaintextLength = 0;
        for (int i = paddedPlaintext.length - 1; i >= 0; i--) {
            if (paddedPlaintext[i] != (byte) 0x00) {
                plaintextLength = i + 1;
                break;
            }
        }
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(paddedPlaintext, 0, plaintext, 0, plaintextLength);
        return plaintext;
    } catch (InvalidCipherTextException e) {
        throw new InvalidCiphertextException(e);
    }
}
Also used : InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) AEADParameters(org.spongycastle.crypto.params.AEADParameters) KeyParameter(org.spongycastle.crypto.params.KeyParameter) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) GCMBlockCipher(org.spongycastle.crypto.modes.GCMBlockCipher)

Example 4 with InvalidCipherTextException

use of org.spongycastle.crypto.InvalidCipherTextException in project jmulticard by ctt-gob-es.

the class AmCryptoProvider method decrypt.

/**
 * Entschlasselt das abergebene ByteArray mit den Parametern die beim @see
 * #init(byte[], long) eingestellt wurden.
 * @param in BytrArray mit den verschlasselten Daten
 * @return ByteArray mit den entschlasselten Daten
 * @throws AmCryptoException On any error.
 */
public final byte[] decrypt(final byte[] in) throws AmCryptoException {
    // number of bytes read from input
    int noBytesRead = 0;
    // number of bytes processed
    int noBytesProcessed = 0;
    try (final ByteArrayInputStream bin = new ByteArrayInputStream(in);
        final ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
        try {
            while ((noBytesRead = bin.read(this.buf)) >= 0) {
                noBytesProcessed = this.decryptCipher.processBytes(this.buf, 0, noBytesRead, this.obuf, 0);
                bout.write(this.obuf, 0, noBytesProcessed);
            }
        } catch (final DataLengthException | IllegalStateException | IOException e) {
            throw new AmCryptoException(e);
        }
        try {
            noBytesProcessed = this.decryptCipher.doFinal(this.obuf, 0);
            bout.write(this.obuf, 0, noBytesProcessed);
            bout.flush();
            return bout.toByteArray();
        } catch (final DataLengthException | IllegalStateException | InvalidCipherTextException | IOException e) {
            throw new AmCryptoException(e);
        }
    } catch (final IOException ioe) {
        throw new AmCryptoException(ioe);
    }
}
Also used : InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) ByteArrayInputStream(java.io.ByteArrayInputStream) DataLengthException(org.spongycastle.crypto.DataLengthException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 5 with InvalidCipherTextException

use of org.spongycastle.crypto.InvalidCipherTextException in project jmulticard by ctt-gob-es.

the class AmCryptoProvider method encrypt.

/**
 * Verschlasselt das abergebene ByteArray mit den Parametern die beim @see
 * #init(byte[], long) eingestellt wurden.
 * @param in ByteArray mit den zu verschlasselnden Daten
 * @return ByteArray mit den entschlasselten Daten.
 * @throws AmCryptoException On any error.
 */
public final byte[] encrypt(final byte[] in) throws AmCryptoException {
    // number of bytes read from input
    int noBytesRead = 0;
    // number of bytes processed
    int noBytesProcessed = 0;
    try (final ByteArrayInputStream bin = new ByteArrayInputStream(in);
        final ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
        try {
            while ((noBytesRead = bin.read(this.buf)) >= 0) {
                noBytesProcessed = this.encryptCipher.processBytes(this.buf, 0, noBytesRead, this.obuf, 0);
                bout.write(this.obuf, 0, noBytesProcessed);
            }
        } catch (final DataLengthException | IllegalStateException | IOException e) {
            throw new AmCryptoException(e);
        }
        try {
            noBytesProcessed = this.encryptCipher.doFinal(this.obuf, 0);
            bout.write(this.obuf, 0, noBytesProcessed);
            bout.flush();
            return bout.toByteArray();
        } catch (final DataLengthException | IllegalStateException | InvalidCipherTextException | IOException e) {
            throw new AmCryptoException(e);
        }
    } catch (final IOException ioe) {
        throw new AmCryptoException(ioe);
    }
}
Also used : InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) ByteArrayInputStream(java.io.ByteArrayInputStream) DataLengthException(org.spongycastle.crypto.DataLengthException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

InvalidCipherTextException (org.spongycastle.crypto.InvalidCipherTextException)9 IOException (java.io.IOException)6 DataLengthException (org.spongycastle.crypto.DataLengthException)4 AESFastEngine (org.spongycastle.crypto.engines.AESFastEngine)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 BufferedBlockCipher (org.spongycastle.crypto.BufferedBlockCipher)2 CBCBlockCipher (org.spongycastle.crypto.modes.CBCBlockCipher)2 GCMBlockCipher (org.spongycastle.crypto.modes.GCMBlockCipher)2 PaddedBufferedBlockCipher (org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher)2 AEADParameters (org.spongycastle.crypto.params.AEADParameters)2 KeyParameter (org.spongycastle.crypto.params.KeyParameter)2 ParametersWithIV (org.spongycastle.crypto.params.ParametersWithIV)2 ECPoint (org.spongycastle.math.ec.ECPoint)2 ByteBuf (io.netty.buffer.ByteBuf)1 BigInteger (java.math.BigInteger)1 SecureRandom (java.security.SecureRandom)1 Message (org.ethereum.net.message.Message)1 DisconnectMessage (org.ethereum.net.p2p.DisconnectMessage)1 HelloMessage (org.ethereum.net.p2p.HelloMessage)1