Search in sources :

Example 1 with ParametersWithIV

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

the class DESedeWrapEngine method wrap.

/**
 * Method wrap
 *
 * @param in    byte array containing the encoded key.
 * @param inOff off set into in that the data starts at.
 * @param inLen length of the data.
 * @return the wrapped bytes.
 */
public byte[] wrap(byte[] in, int inOff, int inLen) {
    if (!forWrapping) {
        throw new IllegalStateException("Not initialized for wrapping");
    }
    byte[] keyToBeWrapped = new byte[inLen];
    System.arraycopy(in, inOff, keyToBeWrapped, 0, inLen);
    // Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
    byte[] CKS = calculateCMSKeyChecksum(keyToBeWrapped);
    // Let WKCKS = WK || CKS where || is concatenation.
    byte[] WKCKS = new byte[keyToBeWrapped.length + CKS.length];
    System.arraycopy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.length);
    System.arraycopy(CKS, 0, WKCKS, keyToBeWrapped.length, CKS.length);
    // Encrypt WKCKS in CBC mode using KEK as the key and IV as the
    // initialization vector. Call the results TEMP1.
    int blockSize = engine.getBlockSize();
    if (WKCKS.length % blockSize != 0) {
        throw new IllegalStateException("Not multiple of block length");
    }
    engine.init(true, paramPlusIV);
    byte[] TEMP1 = new byte[WKCKS.length];
    for (int currentBytePos = 0; currentBytePos != WKCKS.length; currentBytePos += blockSize) {
        engine.processBlock(WKCKS, currentBytePos, TEMP1, currentBytePos);
    }
    // Let TEMP2 = IV || TEMP1.
    byte[] TEMP2 = new byte[this.iv.length + TEMP1.length];
    System.arraycopy(this.iv, 0, TEMP2, 0, this.iv.length);
    System.arraycopy(TEMP1, 0, TEMP2, this.iv.length, TEMP1.length);
    // Reverse the order of the octets in TEMP2 and call the result TEMP3.
    byte[] TEMP3 = reverse(TEMP2);
    // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
    // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
    // result. It is 40 octets long if a 168 bit key is being wrapped.
    ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
    this.engine.init(true, param2);
    for (int currentBytePos = 0; currentBytePos != TEMP3.length; currentBytePos += blockSize) {
        engine.processBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
    }
    return TEMP3;
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV)

Example 2 with ParametersWithIV

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

the class DESedeWrapEngine method unwrap.

/**
 * Method unwrap
 *
 * @param in    byte array containing the wrapped key.
 * @param inOff off set into in that the data starts at.
 * @param inLen length of the data.
 * @return the unwrapped bytes.
 * @throws InvalidCipherTextException
 */
public byte[] unwrap(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {
    if (forWrapping) {
        throw new IllegalStateException("Not set for unwrapping");
    }
    if (in == null) {
        throw new InvalidCipherTextException("Null pointer as ciphertext");
    }
    final int blockSize = engine.getBlockSize();
    if (inLen % blockSize != 0) {
        throw new InvalidCipherTextException("Ciphertext not multiple of " + blockSize);
    }
    /*
      // Check if the length of the cipher text is reasonable given the key
      // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
      // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
      // or inconsistent with the algorithm for which the key is intended,
      // return error.
      //
      // we do not accept 168 bit keys. it has to be 192 bit.
      int lengthA = (estimatedKeyLengthInBit / 8) + 16;
      int lengthB = estimatedKeyLengthInBit % 8;

      if ((lengthA != keyToBeUnwrapped.length) || (lengthB != 0)) {
         throw new XMLSecurityException("empty");
      }
      */
    // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
    // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
    ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
    this.engine.init(false, param2);
    byte[] TEMP3 = new byte[inLen];
    for (int currentBytePos = 0; currentBytePos != inLen; currentBytePos += blockSize) {
        engine.processBlock(in, inOff + currentBytePos, TEMP3, currentBytePos);
    }
    // Reverse the order of the octets in TEMP3 and call the result TEMP2.
    byte[] TEMP2 = reverse(TEMP3);
    // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
    this.iv = new byte[8];
    byte[] TEMP1 = new byte[TEMP2.length - 8];
    System.arraycopy(TEMP2, 0, this.iv, 0, 8);
    System.arraycopy(TEMP2, 8, TEMP1, 0, TEMP2.length - 8);
    // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
    // found in the previous step. Call the result WKCKS.
    this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
    this.engine.init(false, this.paramPlusIV);
    byte[] WKCKS = new byte[TEMP1.length];
    for (int currentBytePos = 0; currentBytePos != WKCKS.length; currentBytePos += blockSize) {
        engine.processBlock(TEMP1, currentBytePos, WKCKS, currentBytePos);
    }
    // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are
    // those octets before the CKS.
    byte[] result = new byte[WKCKS.length - 8];
    byte[] CKStoBeVerified = new byte[8];
    System.arraycopy(WKCKS, 0, result, 0, WKCKS.length - 8);
    System.arraycopy(WKCKS, WKCKS.length - 8, CKStoBeVerified, 0, 8);
    // with the CKS extracted in the above step. If they are not equal, return error.
    if (!checkCMSKeyChecksum(result, CKStoBeVerified)) {
        throw new InvalidCipherTextException("Checksum inside ciphertext is corrupted");
    }
    // WK is the wrapped key, now extracted for use in data decryption.
    return result;
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException)

Example 3 with ParametersWithIV

use of com.github.zhenwei.core.crypto.params.ParametersWithIV 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 4 with ParametersWithIV

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

the class GOST28147WrapEngine method init.

public void init(boolean forWrapping, CipherParameters param) {
    if (param instanceof ParametersWithRandom) {
        ParametersWithRandom pr = (ParametersWithRandom) param;
        param = pr.getParameters();
    }
    ParametersWithUKM pU = (ParametersWithUKM) param;
    cipher.init(forWrapping, pU.getParameters());
    mac.init(new ParametersWithIV(pU.getParameters(), pU.getUKM()));
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) ParametersWithUKM(com.github.zhenwei.core.crypto.params.ParametersWithUKM) ParametersWithRandom(com.github.zhenwei.core.crypto.params.ParametersWithRandom)

Example 5 with ParametersWithIV

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

the class Grain128Engine method init.

/**
 * Initialize a Grain-128 cipher.
 *
 * @param forEncryption Whether or not we are for encryption.
 * @param params        The parameters required to set up the cipher.
 * @throws IllegalArgumentException If the params argument is inappropriate.
 */
public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException {
    /**
     * Grain encryption and decryption is completely symmetrical, so the
     * 'forEncryption' is irrelevant.
     */
    if (!(params instanceof ParametersWithIV)) {
        throw new IllegalArgumentException("Grain-128 Init parameters must include an IV");
    }
    ParametersWithIV ivParams = (ParametersWithIV) params;
    byte[] iv = ivParams.getIV();
    if (iv == null || iv.length != 12) {
        throw new IllegalArgumentException("Grain-128  requires exactly 12 bytes of IV");
    }
    if (!(ivParams.getParameters() instanceof KeyParameter)) {
        throw new IllegalArgumentException("Grain-128 Init parameters must include a key");
    }
    KeyParameter key = (KeyParameter) ivParams.getParameters();
    /**
     * Initialize variables.
     */
    workingIV = new byte[key.getKey().length];
    workingKey = new byte[key.getKey().length];
    lfsr = new int[STATE_SIZE];
    nfsr = new int[STATE_SIZE];
    out = new byte[4];
    System.arraycopy(iv, 0, workingIV, 0, iv.length);
    System.arraycopy(key.getKey(), 0, workingKey, 0, key.getKey().length);
    reset();
}
Also used : ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) KeyParameter(com.github.zhenwei.core.crypto.params.KeyParameter)

Aggregations

ParametersWithIV (com.github.zhenwei.core.crypto.params.ParametersWithIV)71 KeyParameter (com.github.zhenwei.core.crypto.params.KeyParameter)41 CipherParameters (com.github.zhenwei.core.crypto.CipherParameters)20 AEADParameters (com.github.zhenwei.core.crypto.params.AEADParameters)13 InvalidCipherTextException (com.github.zhenwei.core.crypto.InvalidCipherTextException)11 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)7 AsymmetricKeyParameter (com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter)6 IESWithCipherParameters (com.github.zhenwei.core.crypto.params.IESWithCipherParameters)6 ParametersWithRandom (com.github.zhenwei.core.crypto.params.ParametersWithRandom)6 InvalidKeyException (java.security.InvalidKeyException)6 ParametersWithSBox (com.github.zhenwei.core.crypto.params.ParametersWithSBox)5 RC2Parameters (com.github.zhenwei.core.crypto.params.RC2Parameters)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)5 ShortBufferException (javax.crypto.ShortBufferException)5 IvParameterSpec (javax.crypto.spec.IvParameterSpec)5 BadPaddingException (javax.crypto.BadPaddingException)4 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)4 Wrapper (com.github.zhenwei.core.crypto.Wrapper)3 CBCBlockCipher (com.github.zhenwei.core.crypto.modes.CBCBlockCipher)3