Search in sources :

Example 1 with IESWithCipherParameters

use of com.github.zhenwei.core.crypto.params.IESWithCipherParameters in project LinLong-Java by zhenwei1108.

the class EthereumIESEngine method encryptBlock.

private byte[] encryptBlock(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
    byte[] C = null, K = null, K1 = null, K2 = null;
    int len;
    if (cipher == null) {
        // Streaming mode.
        K1 = new byte[inLen];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        if (V.length != 0) {
            System.arraycopy(K, 0, K2, 0, K2.length);
            System.arraycopy(K, K2.length, K1, 0, K1.length);
        } else {
            System.arraycopy(K, 0, K1, 0, K1.length);
            System.arraycopy(K, inLen, K2, 0, K2.length);
        }
        C = new byte[inLen];
        for (int i = 0; i != inLen; i++) {
            C[i] = (byte) (in[inOff + i] ^ K1[i]);
        }
        len = inLen;
    } else {
        // Block cipher mode.
        K1 = new byte[((IESWithCipherParameters) param).getCipherKeySize() / 8];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        System.arraycopy(K, 0, K1, 0, K1.length);
        System.arraycopy(K, K1.length, K2, 0, K2.length);
        // If iv provided use it to initialise the cipher
        if (IV != null) {
            cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV));
        } else {
            cipher.init(true, new KeyParameter(K1));
        }
        C = new byte[cipher.getOutputSize(inLen)];
        len = cipher.processBytes(in, inOff, inLen, C, 0);
        len += cipher.doFinal(C, len);
    }
    // Convert the length of the encoding vector into a byte array.
    byte[] P2 = param.getEncodingV();
    byte[] L2 = null;
    if (V.length != 0) {
        L2 = getLengthTag(P2);
    }
    // Apply the MAC.
    byte[] T = new byte[mac.getMacSize()];
    // Ethereum change:
    // Instead of initializing the mac with the bytes, we initialize with the hash of the bytes.
    // Old code: mac.init(new KeyParameter(K2));
    Digest hash = new SHA256Digest();
    byte[] K2hash = new byte[hash.getDigestSize()];
    hash.reset();
    hash.update(K2, 0, K2.length);
    hash.doFinal(K2hash, 0);
    mac.init(new KeyParameter(K2hash));
    // we also update the mac with the IV:
    mac.update(IV, 0, IV.length);
    // end of Ethereum change.
    mac.update(C, 0, C.length);
    if (P2 != null) {
        mac.update(P2, 0, P2.length);
    }
    if (V.length != 0) {
        mac.update(L2, 0, L2.length);
    }
    // Ethereum change
    mac.update(commonMac, 0, commonMac.length);
    mac.doFinal(T, 0);
    // Output the triple (V,C,T).
    byte[] Output = new byte[V.length + len + T.length];
    System.arraycopy(V, 0, Output, 0, V.length);
    System.arraycopy(C, 0, Output, V.length, len);
    System.arraycopy(T, 0, Output, V.length + len, T.length);
    return Output;
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) SHA256Digest(com.github.zhenwei.core.crypto.digests.SHA256Digest) Digest(com.github.zhenwei.core.crypto.Digest) SHA256Digest(com.github.zhenwei.core.crypto.digests.SHA256Digest) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters)

Example 2 with IESWithCipherParameters

use of com.github.zhenwei.core.crypto.params.IESWithCipherParameters in project LinLong-Java by zhenwei1108.

the class IESCipher method engineDoFinal.

// Finalisation methods
public byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    if (inputLen != 0) {
        buffer.write(input, inputOffset, inputLen);
    }
    byte[] in = buffer.toByteArray();
    buffer.reset();
    // Convert parameters for use in IESEngine
    CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize());
    if (engineSpec.getNonce() != null) {
        params = new ParametersWithIV(params, engineSpec.getNonce());
    }
    DHParameters dhParams = ((DHKeyParameters) key).getParameters();
    byte[] V;
    if (otherKeyParameter != null) {
        try {
            if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
                engine.init(true, otherKeyParameter, key, params);
            } else {
                engine.init(false, key, otherKeyParameter, params);
            }
            return engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    }
    if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
        // Generate the ephemeral key pair
        DHKeyPairGenerator gen = new DHKeyPairGenerator();
        gen.init(new DHKeyGenerationParameters(random, dhParams));
        EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() {

            public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
                byte[] Vloc = new byte[(((DHKeyParameters) keyParameter).getParameters().getP().bitLength() + 7) / 8];
                byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters) keyParameter).getY());
                if (Vtmp.length > Vloc.length) {
                    throw new IllegalArgumentException("Senders's public key longer than expected.");
                } else {
                    System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length);
                }
                return Vloc;
            }
        });
        // Encrypt the buffer
        try {
            engine.init(key, params, kGen);
            return engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) {
        // Decrypt the buffer
        try {
            engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters) key).getParameters()));
            return engine.processBlock(in, 0, in.length);
        } catch (InvalidCipherTextException e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else {
        throw new IllegalStateException("IESCipher not initialised");
    }
}
Also used : EphemeralKeyPairGenerator(com.github.zhenwei.core.crypto.generators.EphemeralKeyPairGenerator) DHKeyParameters(com.github.zhenwei.core.crypto.params.DHKeyParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) KeyEncoder(com.github.zhenwei.core.crypto.KeyEncoder) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) DHParameters(com.github.zhenwei.core.crypto.params.DHParameters) DHKeyPairGenerator(com.github.zhenwei.core.crypto.generators.DHKeyPairGenerator) DHKeyGenerationParameters(com.github.zhenwei.core.crypto.params.DHKeyGenerationParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters) CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) DHIESPublicKeyParser(com.github.zhenwei.core.crypto.parsers.DHIESPublicKeyParser) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters)

Example 3 with IESWithCipherParameters

use of com.github.zhenwei.core.crypto.params.IESWithCipherParameters in project LinLong-Java by zhenwei1108.

the class IESCipher method engineDoFinal.

// Finalisation methods
public byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    if (inputLen != 0) {
        buffer.write(input, inputOffset, inputLen);
    }
    final byte[] in = buffer.toByteArray();
    buffer.reset();
    // Convert parameters for use in IESEngine
    CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize());
    if (engineSpec.getNonce() != null) {
        params = new ParametersWithIV(params, engineSpec.getNonce());
    }
    final ECDomainParameters ecParams = ((ECKeyParameters) key).getParameters();
    final byte[] V;
    if (otherKeyParameter != null) {
        try {
            if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
                engine.init(true, otherKeyParameter, key, params);
            } else {
                engine.init(false, key, otherKeyParameter, params);
            }
            return engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    }
    if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
        // Generate the ephemeral key pair
        ECKeyPairGenerator gen = new ECKeyPairGenerator();
        gen.init(new ECKeyGenerationParameters(ecParams, random));
        final boolean usePointCompression = engineSpec.getPointCompression();
        EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() {

            public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
                return ((ECPublicKeyParameters) keyParameter).getQ().getEncoded(usePointCompression);
            }
        });
        // Encrypt the buffer
        try {
            engine.init(key, params, kGen);
            return engine.processBlock(in, 0, in.length);
        } catch (final Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) {
        // Decrypt the buffer
        try {
            engine.init(key, params, new ECIESPublicKeyParser(ecParams));
            return engine.processBlock(in, 0, in.length);
        } catch (InvalidCipherTextException e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else {
        throw new IllegalStateException("cipher not initialised");
    }
}
Also used : ECKeyPairGenerator(com.github.zhenwei.core.crypto.generators.ECKeyPairGenerator) EphemeralKeyPairGenerator(com.github.zhenwei.core.crypto.generators.EphemeralKeyPairGenerator) ECKeyParameters(com.github.zhenwei.core.crypto.params.ECKeyParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) KeyEncoder(com.github.zhenwei.core.crypto.KeyEncoder) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) ECPublicKeyParameters(com.github.zhenwei.core.crypto.params.ECPublicKeyParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters) CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) ECIESPublicKeyParser(com.github.zhenwei.core.crypto.parsers.ECIESPublicKeyParser) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters) ECKeyGenerationParameters(com.github.zhenwei.core.crypto.params.ECKeyGenerationParameters)

Example 4 with IESWithCipherParameters

use of com.github.zhenwei.core.crypto.params.IESWithCipherParameters in project LinLong-Java by zhenwei1108.

the class IESEngine method decryptBlock.

private byte[] decryptBlock(byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException {
    byte[] M, K, K1, K2;
    int len = 0;
    // Ensure that the length of the input is greater than the MAC in bytes
    if (inLen < V.length + mac.getMacSize()) {
        throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined");
    }
    // note order is important: set up keys, do simple encryptions, check mac, do final encryption.
    if (cipher == null) {
        // Streaming mode.
        K1 = new byte[inLen - V.length - mac.getMacSize()];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        if (V.length != 0) {
            System.arraycopy(K, 0, K2, 0, K2.length);
            System.arraycopy(K, K2.length, K1, 0, K1.length);
        } else {
            System.arraycopy(K, 0, K1, 0, K1.length);
            System.arraycopy(K, K1.length, K2, 0, K2.length);
        }
        // process the message
        M = new byte[K1.length];
        for (int i = 0; i != K1.length; i++) {
            M[i] = (byte) (in_enc[inOff + V.length + i] ^ K1[i]);
        }
    } else {
        // Block cipher mode.
        K1 = new byte[((IESWithCipherParameters) param).getCipherKeySize() / 8];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        System.arraycopy(K, 0, K1, 0, K1.length);
        System.arraycopy(K, K1.length, K2, 0, K2.length);
        CipherParameters cp = new KeyParameter(K1);
        // If IV provide use it to initialize the cipher
        if (IV != null) {
            cp = new ParametersWithIV(cp, IV);
        }
        cipher.init(false, cp);
        M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())];
        // do initial processing
        len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0);
    }
    // Convert the length of the encoding vector into a byte array.
    byte[] P2 = param.getEncodingV();
    byte[] L2 = null;
    if (V.length != 0) {
        L2 = getLengthTag(P2);
    }
    // Verify the MAC.
    int end = inOff + inLen;
    byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end);
    byte[] T2 = new byte[T1.length];
    mac.init(new KeyParameter(K2));
    mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length);
    if (P2 != null) {
        mac.update(P2, 0, P2.length);
    }
    if (V.length != 0) {
        mac.update(L2, 0, L2.length);
    }
    mac.doFinal(T2, 0);
    if (!Arrays.constantTimeAreEqual(T1, T2)) {
        throw new InvalidCipherTextException("invalid MAC");
    }
    if (cipher == null) {
        return M;
    } else {
        len += cipher.doFinal(M, len);
        return Arrays.copyOfRange(M, 0, len);
    }
}
Also used : CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters)

Example 5 with IESWithCipherParameters

use of com.github.zhenwei.core.crypto.params.IESWithCipherParameters in project LinLong-Java by zhenwei1108.

the class IESEngine method encryptBlock.

private byte[] encryptBlock(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
    byte[] C = null, K = null, K1 = null, K2 = null;
    int len;
    if (cipher == null) {
        // Streaming mode.
        K1 = new byte[inLen];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        if (V.length != 0) {
            System.arraycopy(K, 0, K2, 0, K2.length);
            System.arraycopy(K, K2.length, K1, 0, K1.length);
        } else {
            System.arraycopy(K, 0, K1, 0, K1.length);
            System.arraycopy(K, inLen, K2, 0, K2.length);
        }
        C = new byte[inLen];
        for (int i = 0; i != inLen; i++) {
            C[i] = (byte) (in[inOff + i] ^ K1[i]);
        }
        len = inLen;
    } else {
        // Block cipher mode.
        K1 = new byte[((IESWithCipherParameters) param).getCipherKeySize() / 8];
        K2 = new byte[param.getMacKeySize() / 8];
        K = new byte[K1.length + K2.length];
        kdf.generateBytes(K, 0, K.length);
        System.arraycopy(K, 0, K1, 0, K1.length);
        System.arraycopy(K, K1.length, K2, 0, K2.length);
        // If iv provided use it to initialise the cipher
        if (IV != null) {
            cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV));
        } else {
            cipher.init(true, new KeyParameter(K1));
        }
        C = new byte[cipher.getOutputSize(inLen)];
        len = cipher.processBytes(in, inOff, inLen, C, 0);
        len += cipher.doFinal(C, len);
    }
    // Convert the length of the encoding vector into a byte array.
    byte[] P2 = param.getEncodingV();
    byte[] L2 = null;
    if (V.length != 0) {
        L2 = getLengthTag(P2);
    }
    // Apply the MAC.
    byte[] T = new byte[mac.getMacSize()];
    mac.init(new KeyParameter(K2));
    mac.update(C, 0, C.length);
    if (P2 != null) {
        mac.update(P2, 0, P2.length);
    }
    if (V.length != 0) {
        mac.update(L2, 0, L2.length);
    }
    mac.doFinal(T, 0);
    // Output the triple (V,C,T).
    byte[] Output = new byte[V.length + len + T.length];
    System.arraycopy(V, 0, Output, 0, V.length);
    System.arraycopy(C, 0, Output, V.length, len);
    System.arraycopy(T, 0, Output, V.length + len, T.length);
    return Output;
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters)

Aggregations

AsymmetricKeyParameter (com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter)6 IESWithCipherParameters (com.github.zhenwei.core.crypto.params.IESWithCipherParameters)6 ParametersWithIV (com.github.zhenwei.core.crypto.params.ParametersWithIV)6 CipherParameters (com.github.zhenwei.core.crypto.CipherParameters)4 InvalidCipherTextException (com.github.zhenwei.core.crypto.InvalidCipherTextException)4 KeyParameter (com.github.zhenwei.core.crypto.params.KeyParameter)4 Digest (com.github.zhenwei.core.crypto.Digest)2 KeyEncoder (com.github.zhenwei.core.crypto.KeyEncoder)2 SHA256Digest (com.github.zhenwei.core.crypto.digests.SHA256Digest)2 EphemeralKeyPairGenerator (com.github.zhenwei.core.crypto.generators.EphemeralKeyPairGenerator)2 BadBlockException (com.github.zhenwei.provider.jcajce.provider.util.BadBlockException)2 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 BadPaddingException (javax.crypto.BadPaddingException)2 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)2 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)2 ShortBufferException (javax.crypto.ShortBufferException)2 DHKeyPairGenerator (com.github.zhenwei.core.crypto.generators.DHKeyPairGenerator)1 ECKeyPairGenerator (com.github.zhenwei.core.crypto.generators.ECKeyPairGenerator)1