Java Code Examples for javax.crypto.Cipher#getBlockSize()

The following examples show how to use javax.crypto.Cipher#getBlockSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utils.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Deprecated
public static byte[] aesDecrypt(String secretStr, byte[] encrypted) {
   if(encrypted == null || encrypted.length == 0) {
      return null;
   }

   try {
      SecretKey secret = createSecretKey(secretStr);
      Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

      // pull out the iv
      byte[] iv = new byte[cipher.getBlockSize()];
      System.arraycopy(encrypted, 0, iv, 0, iv.length);
      IvParameterSpec ivParam = new IvParameterSpec(iv);

      byte[] data = new byte[encrypted.length - iv.length];
      System.arraycopy(encrypted, iv.length, data, 0, data.length);

      cipher.init(Cipher.DECRYPT_MODE, secret, ivParam);
      return cipher.doFinal(data);
   } catch(Exception e) {
      throw new RuntimeException(e);
   }
}
 
Example 2
Source File: EncryptRSA.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 解密
 * 
 * @param privateKeyArray
 * @param srcBytes
 * @return
 * @throws Exception
 */
public byte[] decrypt(byte[] privateKeyArray, byte[] srcBytes)
		throws Exception {
	PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyArray);
	KeyFactory kf = KeyFactory.getInstance(algorithm);
	PrivateKey keyPrivate = kf.generatePrivate(keySpec);

	Cipher cipher = Cipher.getInstance(algorithm,
			new org.bouncycastle.jce.provider.BouncyCastleProvider());
	cipher.init(Cipher.DECRYPT_MODE, keyPrivate);

	int blockSize = cipher.getBlockSize();
	ByteArrayOutputStream bout = new ByteArrayOutputStream(blockSize);
	int j = 0;
	while (srcBytes.length - j * blockSize > 0) {
		byte[] temp = cipher.doFinal(srcBytes, j * blockSize, blockSize);
		bout.write(temp);
		j++;
	}
	return bout.toByteArray();
}
 
Example 3
Source File: EbicsUserService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * EBICS IG CFONB VF 2.1.4 2012 02 24 - 2.1.3.2 Calcul de la signature:
 *
 * <p>Il convient d’utiliser PKCS1 V1.5 pour chiffrer la clé de chiffrement.
 *
 * <p>EBICS Specification 2.4.2 - 15.2 Workflows at the recipient’s end:
 *
 * <p><b>Decryption of the DES key</b>
 *
 * <p>The leading 256 null bits of the EDEK are removed and the remaining 768 bits are decrypted
 * with the recipient’s secret key of the RSA key system. PDEK is then present. The secret DES key
 * DEK is obtained from the lowest-value 128 bits of PDEK, this is split into the individual keys
 * DEK<SUB>left</SUB> and DEK<SUB>right</SUB>.
 */
public byte[] decrypt(EbicsUser user, byte[] encryptedData, byte[] transactionKey)
    throws AxelorException, GeneralSecurityException, IOException {
  Cipher cipher;
  int blockSize;
  ByteArrayOutputStream outputStream;

  cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
  cipher.init(
      Cipher.DECRYPT_MODE, ebicsService.getPrivateKey(user.getE002Certificate().getPrivateKey()));
  blockSize = cipher.getBlockSize();
  outputStream = new ByteArrayOutputStream();
  for (int j = 0; j * blockSize < transactionKey.length; j++) {
    outputStream.write(cipher.doFinal(transactionKey, j * blockSize, blockSize));
  }

  return decryptData(encryptedData, outputStream.toByteArray());
}
 
Example 4
Source File: DkCrypto.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts data using specified key and initial vector.
 * @param baseKey encryption key to use
 * @param ciphertext  encrypted data to be decrypted
 * @param usage ignored
 */
public byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
    byte[] ciphertext, int start, int len)
    throws GeneralSecurityException {

    if (debug) {
        System.err.println("usage: " + usage);
        if (ivec != null) {
            traceOutput("old_state.ivec", ivec, 0, ivec.length);
        }
        traceOutput("ciphertext", ciphertext, start, Math.min(len, 32));
        traceOutput("baseKey", baseKey, 0, baseKey.length);
    }

    Cipher decCipher = getCipher(baseKey, ivec, Cipher.DECRYPT_MODE);

    int blockSize = decCipher.getBlockSize();

    if ((len % blockSize) != 0) {
        throw new GeneralSecurityException(
            "length of data to be decrypted (" + len +
            ") is not a multiple of the blocksize (" + blockSize + ")");
    }

    byte[] decrypted = decCipher.doFinal(ciphertext, start, len);

    if (debug) {
        traceOutput("decrypted", decrypted, 0,
            Math.min(decrypted.length, 32));
    }

    return decrypted;
}
 
Example 5
Source File: DkCrypto.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] dr(byte[] key, byte[] constant)
    throws GeneralSecurityException {

    Cipher encCipher = getCipher(key, null, Cipher.ENCRYPT_MODE);
    int blocksize = encCipher.getBlockSize();

    if (constant.length != blocksize) {
        constant = nfold(constant, blocksize * 8);
    }
    byte[] toBeEncrypted = constant;

    int keybytes = (getKeySeedLength()>>3);  // from bits to bytes
    byte[] rawkey = new byte[keybytes];
    int posn = 0;

    /* loop encrypting the blocks until enough key bytes are generated */
    int n = 0, len;
    while (n < keybytes) {
        if (debug) {
            System.err.println("Encrypting: " +
                bytesToString(toBeEncrypted));
        }

        byte[] cipherBlock = encCipher.doFinal(toBeEncrypted);
        if (debug) {
            System.err.println("K: " + ++posn + " = " +
                bytesToString(cipherBlock));
        }

        len = (keybytes - n <= cipherBlock.length ? (keybytes - n) :
            cipherBlock.length);
        if (debug) {
            System.err.println("copying " + len + " key bytes");
        }
        System.arraycopy(cipherBlock, 0, rawkey, n, len);
        n += len;
        toBeEncrypted = cipherBlock;
    }
    return rawkey;
}
 
Example 6
Source File: DkCrypto.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] dr(byte[] key, byte[] constant)
    throws GeneralSecurityException {

    Cipher encCipher = getCipher(key, null, Cipher.ENCRYPT_MODE);
    int blocksize = encCipher.getBlockSize();

    if (constant.length != blocksize) {
        constant = nfold(constant, blocksize * 8);
    }
    byte[] toBeEncrypted = constant;

    int keybytes = (getKeySeedLength()>>3);  // from bits to bytes
    byte[] rawkey = new byte[keybytes];
    int posn = 0;

    /* loop encrypting the blocks until enough key bytes are generated */
    int n = 0, len;
    while (n < keybytes) {
        if (debug) {
            System.err.println("Encrypting: " +
                bytesToString(toBeEncrypted));
        }

        byte[] cipherBlock = encCipher.doFinal(toBeEncrypted);
        if (debug) {
            System.err.println("K: " + ++posn + " = " +
                bytesToString(cipherBlock));
        }

        len = (keybytes - n <= cipherBlock.length ? (keybytes - n) :
            cipherBlock.length);
        if (debug) {
            System.err.println("copying " + len + " key bytes");
        }
        System.arraycopy(cipherBlock, 0, rawkey, n, len);
        n += len;
        toBeEncrypted = cipherBlock;
    }
    return rawkey;
}
 
Example 7
Source File: EncryptingWritableByteChannel.java    From alfresco-simple-content-stores with Apache License 2.0 5 votes vote down vote up
public EncryptingWritableByteChannel(final WritableByteChannel delegateChannel, final Key key)
{
    this.delegateChannel = delegateChannel;

    try
    {
        Cipher cipher = Cipher.getInstance(key.getAlgorithm());
        if (cipher.getBlockSize() == 0)
        {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            this.cipher = cipher;
        }
        else
        {
            cipher = Cipher.getInstance(key.getAlgorithm() + "/CBC/PKCS5Padding");

            final byte[] iv = new byte[cipher.getBlockSize()];
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            this.cipher = cipher;
        }
    }
    catch (final NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException e)
    {
        LOGGER.error("Error initializing cipher for key {}", key, e);
        throw new AlfrescoRuntimeException("Error initialising cipher", e);
    }
}
 
Example 8
Source File: DecrypterImpl.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public String decrypt(String encrypted) {
  try {
    byte[] decoded = BaseEncoding.base64Url().decode(encrypted);
    Cipher cipher;
    switch (transformation) {
      case AES_CBC_NOPADDING:
        cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key, generateIv(cipher));
        break;
      case RSA_ECB_PKCS1:
        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);        
        break;
      default:
        throw new AssertionError("How could this happen...");
    }
    byte[] decrypted = cipher.doFinal(decoded);
    if (decrypted == null || decrypted.length <= cipher.getBlockSize()) {
      throw new RuntimeException("incorrect decrypted text.");
    }
    byte[] data = new byte[decrypted.length - cipher.getBlockSize()];
    System.arraycopy(decrypted, cipher.getBlockSize(), data, 0, data.length);
    return new String(data, Charsets.UTF_8);
  } catch (BadPaddingException
      | IllegalBlockSizeException
      | InvalidAlgorithmParameterException
      | InvalidKeyException
      | NoSuchAlgorithmException
      | NoSuchPaddingException e) {
    monitor.severe(() -> format("Error decrypting data, length: %s", encrypted.length()), e);
    throw new RuntimeException(e);
  }
}
 
Example 9
Source File: Record.java    From statelearner with Apache License 2.0 5 votes vote down vote up
public void encrypt(Cipher cipher, SecureRandom rand) throws Exception {
	byte[] iv = new byte[] {};
	int new_len;
	
	if(protocolVersion.val < ProtocolVersion.TLS11.val) {
		new_len = (int) (Math.ceil((payload.length) / cipher.getBlockSize()) + 1) * cipher.getBlockSize();
	}
	else {
		new_len = (int) (Math.ceil((payload.length)/ cipher.getBlockSize()) + 2) * cipher.getBlockSize();
	
  		  	// Generate random IV
		iv = new byte[cipher.getBlockSize()];
		rand.nextBytes(iv);
	}
	
	byte[] tmp = new byte[new_len];

	// Copy IV
	System.arraycopy(iv, 0, tmp, 0, iv.length);

	// Add payload
	System.arraycopy(payload, 0, tmp, iv.length, payload.length);
		
	// Add padding
	int pad_len = new_len - iv.length - payload.length;
	for(int i = iv.length + payload.length; i < tmp.length; i++)
		tmp[i] = (byte)(pad_len-1);

	// Encrypt payload
	payload = cipher.update(tmp);
	
	// Update length
	length = payload.length;
       lengthMSB = (byte)(0xFF & (length >>> 8));
       lengthLSB = (byte)(0xFF & length);
}
 
Example 10
Source File: AES.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 加密
 * @param data 数据
 * @param key 密码
 * @param iv 初始化向量
 * @return
 */
public static String encrypt(String data,String key,String iv) { 
	if(iv == null || iv.length() != 16){//如果iv为空,则使用默认值
		iv = IV_DEFAULT;
	}
	
	
       try { 
           Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 
           int blockSize = cipher.getBlockSize(); 
       
           byte[] dataBytes = data.getBytes(); 
           int plaintextLength = dataBytes.length; 
           if (plaintextLength % blockSize != 0) { 
               plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); 
           } 
   
           byte[] plaintext = new byte[plaintextLength]; 
           System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); 
       
           SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); 
           IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); 
       
           cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); 
           byte[] encrypted = cipher.doFinal(plaintext); 
       
           return Base64.encode(encrypted); 
   
       } catch (Exception e) { 
       	if (logger.isErrorEnabled()) {
            logger.error("加密",e);
        }
       } 
       return null; 
   }
 
Example 11
Source File: DkCrypto.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypts data using specified key and initial vector.
 * @param baseKey encryption key to use
 * @param ciphertext  encrypted data to be decrypted
 * @param usage ignored
 */
public byte[] decryptRaw(byte[] baseKey, int usage, byte[] ivec,
    byte[] ciphertext, int start, int len)
    throws GeneralSecurityException {

    if (debug) {
        System.err.println("usage: " + usage);
        if (ivec != null) {
            traceOutput("old_state.ivec", ivec, 0, ivec.length);
        }
        traceOutput("ciphertext", ciphertext, start, Math.min(len, 32));
        traceOutput("baseKey", baseKey, 0, baseKey.length);
    }

    Cipher decCipher = getCipher(baseKey, ivec, Cipher.DECRYPT_MODE);

    int blockSize = decCipher.getBlockSize();

    if ((len % blockSize) != 0) {
        throw new GeneralSecurityException(
            "length of data to be decrypted (" + len +
            ") is not a multiple of the blocksize (" + blockSize + ")");
    }

    byte[] decrypted = decCipher.doFinal(ciphertext, start, len);

    if (debug) {
        traceOutput("decrypted", decrypted, 0,
            Math.min(decrypted.length, 32));
    }

    return decrypted;
}
 
Example 12
Source File: CipherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper routine to decrypt fromm a byte array and write the
 * application data straight to an output array with minimal
 * buffer copies. The confounder and the padding are stored
 * separately and not copied into this output array.
 * @param key the DES key to use
 * @param cipherText the encrypted data
 * @param offset the offset for the encrypted data
 * @param len the length of the encrypted data
 * @param dataOutBuf the output buffer where the application data
 * should be writte
 * @param dataOffset the offser where the application data should
 * be written.
 * @throws GSSException is an error occurs while decrypting the
 * data
 */
private void desCbcDecrypt(WrapToken token, byte[] key, byte[] cipherText,
    int offset, int len, byte[] dataOutBuf, int dataOffset)
     throws GSSException {

    try {

        int temp = 0;

        Cipher des = getInitializedDes(false, key, ZERO_IV);

        /*
         * Remove the counfounder first.
         * CONFOUNDER_SIZE is one DES block ie 8 bytes.
         */
        temp = des.update(cipherText, offset, WrapToken.CONFOUNDER_SIZE,
                          token.confounder);
        // temp should be CONFOUNDER_SIZE
        // debug("\n\ttemp is " + temp + " and CONFOUNDER_SIZE is "
        //  + CONFOUNDER_SIZE);

        offset += WrapToken.CONFOUNDER_SIZE;
        len -= WrapToken.CONFOUNDER_SIZE;

        /*
         * len is a multiple of 8 due to padding.
         * Decrypt all blocks directly into the output buffer except for
         * the very last block. Remove the trailing padding bytes from the
         * very last block and copy that into the output buffer.
         */

        int blockSize = des.getBlockSize();
        int numBlocks = len / blockSize - 1;

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            temp = des.update(cipherText, offset, blockSize,
                              dataOutBuf, dataOffset);
            // temp should be blockSize
            // debug("\n\ttemp is " + temp + " and blockSize is "
            //    + blockSize);

            offset += blockSize;
            dataOffset += blockSize;
        }

        // Now process the last block
        byte[] finalBlock = new byte[blockSize];
        des.update(cipherText, offset, blockSize, finalBlock);

        des.doFinal();

        /*
         * There is always at least one padding byte. The padding bytes
         * are all the value of the number of padding bytes.
         */

        int padSize = finalBlock[blockSize - 1];
        if (padSize < 1  || padSize > 8)
            throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                                    "Invalid padding on Wrap Token");
        token.padding = WrapToken.pads[padSize];
        blockSize -= padSize;

        // Copy this last block into the output buffer
        System.arraycopy(finalBlock, 0, dataOutBuf, dataOffset,
                         blockSize);

    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 13
Source File: CipherHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Computes the DesCbc checksum based on the algorithm published in FIPS
 * Publication 113. This involves applying padding to the data passed
 * in, then performing DesCbc encryption on the data with a zero initial
 * vector, and finally returning the last 8 bytes of the encryption
 * result.
 *
 * @param key the bytes for the DES key
 * @param header a header to process first before the data is.
 * @param data the data to checksum
 * @param offset the offset where the data begins
 * @param len the length of the data
 * @throws GSSException when an error occuse in the encryption
 */
private byte[] getDesCbcChecksum(byte key[],
                                 byte[] header,
                                 byte[] data, int offset, int len)
    throws GSSException {

    Cipher des = getInitializedDes(true, key, ZERO_IV);

    int blockSize = des.getBlockSize();

    /*
     * Here the data need not be a multiple of the blocksize
     * (8). Encrypt and throw away results for all blocks except for
     * the very last block.
     */

    byte[] finalBlock = new byte[blockSize];

    int numBlocks = len / blockSize;
    int lastBytes = len % blockSize;
    if (lastBytes == 0) {
        // No need for padding. Save last block from application data
        numBlocks -= 1;
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, blockSize);
    } else {
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, lastBytes);
        // Zero padding automatically done
    }

    try {
        byte[] temp = new byte[Math.max(blockSize,
            (header == null? blockSize : header.length))];

        if (header != null) {
            // header will be null when doing DES-MD5 Checksum
            des.update(header, 0, header.length, temp, 0);
        }

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            des.update(data, offset, blockSize,
                       temp, 0);
            offset += blockSize;
        }

        // Now process the final block
        byte[] retVal = new byte[blockSize];
        des.update(finalBlock, 0, blockSize, retVal, 0);
        des.doFinal();

        return retVal;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES Cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 14
Source File: Encryption.java    From gradle-credentials-plugin with Apache License 2.0 4 votes vote down vote up
private static Encryption createEncryptionThrowingException(char[] passphrase) throws GeneralSecurityException {
    // define a salt to prevent dictionary attacks (ideally, the salt would be
    // regenerated each time and stored alongside the encrypted text)
    byte[] salt = {
            (byte) 0x1F, (byte) 0x13, (byte) 0xE5, (byte) 0xB2,
            (byte) 0x49, (byte) 0x2C, (byte) 0xC3, (byte) 0x3C
    };

    // use a high iteration count to slow down the decryption speed
    int iterationCount = 65536;

    // use the maximum key length that does not require to install the JRE Security Extension
    int keyLength = 128;

    // provide password, salt, iteration count, and key length for generating the PBEKey
    KeySpec pbeKeySpec = new PBEKeySpec(passphrase, salt, iterationCount, keyLength);

    // create a secret (symmetric) key using PBE with SHA1 and AES
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey tmpKey = keyFac.generateSecret(pbeKeySpec);
    SecretKey pbeKey = new SecretKeySpec(tmpKey.getEncoded(), "AES");

    // create a fixed iv spec that can be used both for encryption and for later decryption
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    int blockSize = cipher.getBlockSize();
    byte[] iv = new byte[blockSize];
    for (int i = 0; i < iv.length; i++) {
        iv[i] = (byte) i;
    }
    AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);

    // initialize the encryption cipher
    Cipher pbeEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    pbeEcipher.init(Cipher.ENCRYPT_MODE, pbeKey, ivSpec);

    // initialize the decryption cipher
    Cipher pbeDcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    pbeDcipher.init(Cipher.DECRYPT_MODE, pbeKey, ivSpec);

    return new Encryption(pbeEcipher, pbeDcipher);
}
 
Example 15
Source File: AESKeyedCipherProvider.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, SecretKey key, byte[] iv,
                                      boolean encryptMode) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (!encryptionMethod.isKeyedCipher()) {
        throw new IllegalArgumentException(encryptionMethod.name() + " requires a PBECipherProvider");
    }

    String algorithm = encryptionMethod.getAlgorithm();
    String provider = encryptionMethod.getProvider();

    if (key == null) {
        throw new IllegalArgumentException("The key must be specified");
    }

    if (!isValidKeyLength(key)) {
        throw new IllegalArgumentException("The key must be of length [" + StringUtils.join(VALID_KEY_LENGTHS, ", ") + "]");
    }

    Cipher cipher = Cipher.getInstance(algorithm, provider);
    final String operation = encryptMode ? "encrypt" : "decrypt";

    boolean ivIsInvalid = false;

    // If an IV was not provided already, generate a random IV and inject it in the cipher
    int ivLength = cipher.getBlockSize();
    if (iv.length != ivLength) {
        logger.warn("An IV was provided of length {} bytes for {}ion but should be {} bytes", iv.length, operation, ivLength);
        ivIsInvalid = true;
    }

    final byte[] emptyIv = new byte[ivLength];
    if (Arrays.equals(iv, emptyIv)) {
        logger.warn("An empty IV was provided of length {} for {}ion", iv.length, operation);
        ivIsInvalid = true;
    }

    if (ivIsInvalid) {
        if (encryptMode) {
            logger.warn("Generating new IV. The value can be obtained in the calling code by invoking 'cipher.getIV()';");
            iv = generateIV();
        } else {
            // Can't decrypt without an IV
            throw new IllegalArgumentException("Cannot decrypt without a valid IV");
        }
    }
    cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

    return cipher;
}
 
Example 16
Source File: CipherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper routine to decrypt from an InputStream and write the
 * application data straight to an output array with minimal
 * buffer copies. The confounder and the padding are stored
 * separately and not copied into this output array.
 * @param key the DES key to use
 * @param is the InputStream from which the cipher text should be
 * read
 * @param len the length of the ciphertext data
 * @param dataOutBuf the output buffer where the application data
 * should be writte
 * @param dataOffset the offser where the application data should
 * be written.
 * @throws GSSException is an error occurs while decrypting the
 * data
 */
private void desCbcDecrypt(WrapToken token, byte[] key,
    InputStream is, int len, byte[] dataOutBuf, int dataOffset)
    throws GSSException, IOException {

    int temp = 0;

    Cipher des = getInitializedDes(false, key, ZERO_IV);

    WrapTokenInputStream truncatedInputStream =
        new WrapTokenInputStream(is, len);
    CipherInputStream cis = new CipherInputStream(truncatedInputStream,
                                                  des);
    /*
     * Remove the counfounder first.
     * CONFOUNDER_SIZE is one DES block ie 8 bytes.
     */
    temp = cis.read(token.confounder);

    len -= temp;
    // temp should be CONFOUNDER_SIZE
    // debug("Got " + temp + " bytes; CONFOUNDER_SIZE is "
    //     + CONFOUNDER_SIZE + "\n");
    // debug("Confounder is " + getHexBytes(confounder) + "\n");


    /*
     * len is a multiple of 8 due to padding.
     * Decrypt all blocks directly into the output buffer except for
     * the very last block. Remove the trailing padding bytes from the
     * very last block and copy that into the output buffer.
     */

    int blockSize = des.getBlockSize();
    int numBlocks = len / blockSize - 1;

    // Iterate over all but the last block
    for (int i = 0; i < numBlocks; i++) {
        // debug("dataOffset is " + dataOffset + "\n");
        temp = cis.read(dataOutBuf, dataOffset, blockSize);

        // temp should be blockSize
        // debug("Got " + temp + " bytes and blockSize is "
        //    + blockSize + "\n");
        // debug("Bytes are: "
        //    + getHexBytes(dataOutBuf, dataOffset, temp) + "\n");
        dataOffset += blockSize;
    }

    // Now process the last block
    byte[] finalBlock = new byte[blockSize];
    // debug("Will call read on finalBlock" + "\n");
    temp = cis.read(finalBlock);
    // temp should be blockSize
    /*
      debug("Got " + temp + " bytes and blockSize is "
      + blockSize + "\n");
      debug("Bytes are: "
      + getHexBytes(finalBlock, 0, temp) + "\n");
      debug("Will call doFinal" + "\n");
    */
    try {
        des.doFinal();
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }

    /*
     * There is always at least one padding byte. The padding bytes
     * are all the value of the number of padding bytes.
     */

    int padSize = finalBlock[blockSize - 1];
    if (padSize < 1  || padSize > 8)
        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                               "Invalid padding on Wrap Token");
    token.padding = WrapToken.pads[padSize];
    blockSize -= padSize;

    // Copy this last block into the output buffer
    System.arraycopy(finalBlock, 0, dataOutBuf, dataOffset,
                     blockSize);
}
 
Example 17
Source File: CipherHelper.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Computes the DesCbc checksum based on the algorithm published in FIPS
 * Publication 113. This involves applying padding to the data passed
 * in, then performing DesCbc encryption on the data with a zero initial
 * vector, and finally returning the last 8 bytes of the encryption
 * result.
 *
 * @param key the bytes for the DES key
 * @param header a header to process first before the data is.
 * @param data the data to checksum
 * @param offset the offset where the data begins
 * @param len the length of the data
 * @throws GSSException when an error occuse in the encryption
 */
private byte[] getDesCbcChecksum(byte key[],
                                 byte[] header,
                                 byte[] data, int offset, int len)
    throws GSSException {

    Cipher des = getInitializedDes(true, key, ZERO_IV);

    int blockSize = des.getBlockSize();

    /*
     * Here the data need not be a multiple of the blocksize
     * (8). Encrypt and throw away results for all blocks except for
     * the very last block.
     */

    byte[] finalBlock = new byte[blockSize];

    int numBlocks = len / blockSize;
    int lastBytes = len % blockSize;
    if (lastBytes == 0) {
        // No need for padding. Save last block from application data
        numBlocks -= 1;
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, blockSize);
    } else {
        System.arraycopy(data, offset + numBlocks*blockSize,
                         finalBlock, 0, lastBytes);
        // Zero padding automatically done
    }

    try {
        byte[] temp = new byte[Math.max(blockSize,
            (header == null? blockSize : header.length))];

        if (header != null) {
            // header will be null when doing DES-MD5 Checksum
            des.update(header, 0, header.length, temp, 0);
        }

        // Iterate over all but the last block
        for (int i = 0; i < numBlocks; i++) {
            des.update(data, offset, blockSize,
                       temp, 0);
            offset += blockSize;
        }

        // Now process the final block
        byte[] retVal = new byte[blockSize];
        des.update(finalBlock, 0, blockSize, retVal, 0);
        des.doFinal();

        return retVal;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES Cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example 18
Source File: EncryptedOutputStream.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public EncryptedOutputStream( Cipher cf, OutputStream os ) throws Exception {
	this.os	= os;
	this.cf	= cf;
	bufSize = cf.getBlockSize();
	buffer 	= new byte[bufSize];
}
 
Example 19
Source File: EncrypterImpl.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private static final IvParameterSpec generateIv(Cipher cipher) throws NoSuchAlgorithmException {
  SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
  byte[] iv = new byte[cipher.getBlockSize()];
  randomSecureRandom.nextBytes(iv);
  return new IvParameterSpec(iv);
}
 
Example 20
Source File: CipherHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper routine to decrypt from an InputStream and write the
 * application data straight to an output array with minimal
 * buffer copies. The confounder and the padding are stored
 * separately and not copied into this output array.
 * @param key the DES key to use
 * @param is the InputStream from which the cipher text should be
 * read
 * @param len the length of the ciphertext data
 * @param dataOutBuf the output buffer where the application data
 * should be writte
 * @param dataOffset the offser where the application data should
 * be written.
 * @throws GSSException is an error occurs while decrypting the
 * data
 */
private void desCbcDecrypt(WrapToken token, byte[] key,
    InputStream is, int len, byte[] dataOutBuf, int dataOffset)
    throws GSSException, IOException {

    int temp = 0;

    Cipher des = getInitializedDes(false, key, ZERO_IV);

    WrapTokenInputStream truncatedInputStream =
        new WrapTokenInputStream(is, len);
    CipherInputStream cis = new CipherInputStream(truncatedInputStream,
                                                  des);
    /*
     * Remove the counfounder first.
     * CONFOUNDER_SIZE is one DES block ie 8 bytes.
     */
    temp = cis.read(token.confounder);

    len -= temp;
    // temp should be CONFOUNDER_SIZE
    // debug("Got " + temp + " bytes; CONFOUNDER_SIZE is "
    //     + CONFOUNDER_SIZE + "\n");
    // debug("Confounder is " + getHexBytes(confounder) + "\n");


    /*
     * len is a multiple of 8 due to padding.
     * Decrypt all blocks directly into the output buffer except for
     * the very last block. Remove the trailing padding bytes from the
     * very last block and copy that into the output buffer.
     */

    int blockSize = des.getBlockSize();
    int numBlocks = len / blockSize - 1;

    // Iterate over all but the last block
    for (int i = 0; i < numBlocks; i++) {
        // debug("dataOffset is " + dataOffset + "\n");
        temp = cis.read(dataOutBuf, dataOffset, blockSize);

        // temp should be blockSize
        // debug("Got " + temp + " bytes and blockSize is "
        //    + blockSize + "\n");
        // debug("Bytes are: "
        //    + getHexBytes(dataOutBuf, dataOffset, temp) + "\n");
        dataOffset += blockSize;
    }

    // Now process the last block
    byte[] finalBlock = new byte[blockSize];
    // debug("Will call read on finalBlock" + "\n");
    temp = cis.read(finalBlock);
    // temp should be blockSize
    /*
      debug("Got " + temp + " bytes and blockSize is "
      + blockSize + "\n");
      debug("Bytes are: "
      + getHexBytes(finalBlock, 0, temp) + "\n");
      debug("Will call doFinal" + "\n");
    */
    try {
        des.doFinal();
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }

    /*
     * There is always at least one padding byte. The padding bytes
     * are all the value of the number of padding bytes.
     */

    int padSize = finalBlock[blockSize - 1];
    if (padSize < 1  || padSize > 8)
        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                               "Invalid padding on Wrap Token");
    token.padding = WrapToken.pads[padSize];
    blockSize -= padSize;

    // Copy this last block into the output buffer
    System.arraycopy(finalBlock, 0, dataOutBuf, dataOffset,
                     blockSize);
}