Example usage for javax.crypto Cipher getBlockSize

List of usage examples for javax.crypto Cipher getBlockSize

Introduction

In this page you can find the example usage for javax.crypto Cipher getBlockSize.

Prototype

public final int getBlockSize() 

Source Link

Document

Returns the block size (in bytes).

Usage

From source file:org.auscope.portal.server.web.controllers.GridLoginController.java

/**
 * Uses a cipher to decrypt data from an input stream.
 *//*from   w  w w.  j  a  v  a 2  s .  c  o  m*/
private String decryptString(InputStream in, Cipher cipher) throws GeneralSecurityException, IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBlock = new byte[blockSize];
    byte[] outBlock = new byte[outputSize];
    int bytesRead;
    do {
        bytesRead = in.read(inBlock);
        if (bytesRead == blockSize) {
            int len = cipher.update(inBlock, 0, blockSize, outBlock);
            output.write(outBlock, 0, len);
        }
    } while (bytesRead == blockSize);

    if (bytesRead > 0) {
        outBlock = cipher.doFinal(inBlock, 0, bytesRead);
    } else {
        outBlock = cipher.doFinal();
    }
    output.write(outBlock);
    return output.toString();
}

From source file:org.apache.nifi.processors.standard.util.crypto.AESKeyedCipherProvider.java

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");
    }//from   www  .ja  v  a2 s.  c om

    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;
}

From source file:uk.ac.ox.webauth.crypto.DesCbcCrc.java

/**
 * From RFC 3961:/*from w ww.  ja v  a  2  s  .c o  m*/
 * <pre>
 *   +-----------+----------+---------+-----+
 *   |confounder | checksum | msg-seq | pad |
 *   +-----------+----------+---------+-----+
 * </pre>
 */
@Override
public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException {
    // decrypt the data
    Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
    IvParameterSpec iv = new IvParameterSpec(key.getEncoded());
    cipher.init(DECRYPT_MODE, key, iv);
    byte[] data = cipher.doFinal(cipherData);

    // split out the CRC checksum (4 bytes) and check it
    byte[] checksum = new byte[4];
    System.arraycopy(data, cipher.getBlockSize(), checksum, 0, checksum.length);
    Arrays.fill(data, cipher.getBlockSize(), cipher.getBlockSize() + checksum.length, (byte) 0);
    if (!Arrays.equals(checksum, modifiedCRC32(data))) {
        throw new GeneralSecurityException("Checksum failure.");
    }

    // return an ASN.1 object
    InputStream is = new ByteArrayInputStream(data);
    is.skip(cipher.getBlockSize() + checksum.length);
    ASN1InputStream ais = new ASN1InputStream(is);

    return (ASN1Encodable) ais.readObject();
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

private byte[] decryptBytes(byte[] encryptedBytes, String algorithmUri, Key key)
        throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
    Cipher cipher = getCipher(Cipher.DECRYPT_MODE, algorithmUri);

    // Extract IV from the beginning of the encrypted bytes
    int ivLen = cipher.getBlockSize();
    byte[] ivBytes = new byte[ivLen];
    System.arraycopy(encryptedBytes, 0, ivBytes, 0, ivLen);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    cipher.init(Cipher.DECRYPT_MODE, key, iv);

    byte[] decryptedData = cipher.doFinal(encryptedBytes, ivLen, encryptedBytes.length - ivLen);

    return decryptedData;
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

@Override
public byte[] encrypt(ASN1Encodable o) throws IOException, GeneralSecurityException {
    // derive our decryption and hmac keys as per RFC 3961
    // first work out the "well known constant"s for the different keys
    byte[] wkcKe = new byte[5];
    wkcKe[0] = (byte) ((keyUsage >> 24) & 0xFF);
    wkcKe[1] = (byte) ((keyUsage >> 16) & 0xFF);
    wkcKe[2] = (byte) ((keyUsage >> 8) & 0xFF);
    wkcKe[3] = (byte) (keyUsage & 0xFF);
    wkcKe[4] = (byte) 0xAA;
    byte[] wkcKi = (byte[]) wkcKe.clone();
    wkcKi[4] = (byte) 0x55;

    // then make the keys
    // RFC 3961: Derived Key = DK(Base Key, Well-Known Constant)
    SecretKey ke = new SecretKeySpec(dk(key.getEncoded(), wkcKe), "DESede");
    SecretKey ki = new SecretKeySpec(dk(key.getEncoded(), wkcKi), "DESede");

    // setup the Cipher so we can get the block size
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    cipher.init(ENCRYPT_MODE, ke, IV);/*from   w w w .j  a v a 2 s.co m*/
    int blockSize = cipher.getBlockSize();

    // set up the byte array with data
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] confounder = new byte[blockSize];
    synchronized (rand) {
        rand.nextBytes(confounder);
    }
    baos.write(confounder);
    baos.write(o.getDEREncoded());

    // PKCS7 padding
    byte[] pad = new byte[blockSize - (baos.size() % blockSize)];
    Arrays.fill(pad, (byte) pad.length);
    baos.write(pad);
    byte[] data = baos.toByteArray();

    // calculate the checksum
    Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
    hmacSHA1.init(ki);
    byte[] checksum = hmacSHA1.doFinal(data);

    // now encrypt the data
    baos = new ByteArrayOutputStream();
    baos.write(cipher.doFinal(data));
    baos.write(checksum);

    return baos.toByteArray();
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

public static InputStream getEncryptedInputStream(UploadPartRequest request, Cipher symmetricCipher) {
    try {//w  ww.  jav a  2 s. co m
        InputStream originalInputStream = request.getInputStream();
        if (request.getFile() != null) {
            originalInputStream = new InputSubstream(new RepeatableFileInputStream(request.getFile()),
                    request.getFileOffset(), request.getPartSize(), request.isLastPart());
        }

        originalInputStream = new CipherInputStream(originalInputStream, symmetricCipher);

        if (request.isLastPart() == false) {
            // We want to prevent the final padding from being sent on the stream...
            originalInputStream = new InputSubstream(originalInputStream, 0, request.getPartSize(), false);
        }

        long partSize = request.getPartSize();
        int cipherBlockSize = symmetricCipher.getBlockSize();
        return new ByteRangeCapturingInputStream(originalInputStream, partSize - cipherBlockSize, partSize);
    } catch (Exception e) {
        throw new LunacloudClientException("Unable to create cipher input stream: " + e.getMessage(), e);
    }
}

From source file:org.signserver.server.cryptotokens.PKCS11CryptoToken.java

private byte[] cryptDataBytes(Cipher cipher, byte[] dataBytes, boolean encription)
        throws BadPaddingException, IllegalBlockSizeException, IOException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    if (blockSize == 0) {
        blockSize = outputSize - 11;/*w  w  w .ja v  a2  s.  c  o  m*/
    }

    int readingBlockSize = 0;
    if (encription) {
        readingBlockSize = blockSize;
    } else {
        readingBlockSize = outputSize;
    }

    int inLen = dataBytes.length;
    int fullBlockCount = inLen / readingBlockSize;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int inOffset = 0;
    for (int i = 0; i < fullBlockCount; i++) {
        outputStream.write(cipher.doFinal(dataBytes, inOffset, readingBlockSize));
        inOffset += readingBlockSize;
    }
    if (inOffset < inLen) {
        outputStream.write(cipher.doFinal(dataBytes, inOffset, inLen - inOffset));
    }
    return outputStream.toByteArray();
}

From source file:org.apache.ws.security.message.WSSecEncryptedKey.java

/**
 * Encrypt the symmetric key data and prepare the EncryptedKey element
 * // w w w. j a  va  2  s  .co m
 * This method does the most work for to prepare the EncryptedKey element.
 * It is also used by the WSSecEncrypt sub-class.
 * 
 * @param keyBytes The bytes that represent the symmetric key
 * @param remoteCert The certificate that contains the public key to encrypt the
 *                   symmetric key data
 * @param crypto An instance of the Crypto API to handle keystore and certificates
 * @throws WSSecurityException
 */
protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert, Crypto crypto)
        throws WSSecurityException {
    String certUri = UUIDGenerator.getUUID();
    Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
    try {
        cipher.init(Cipher.ENCRYPT_MODE, remoteCert.getPublicKey());
    } catch (InvalidKeyException e) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e);
    }
    if (doDebug) {
        log.debug("cipher blksize: " + cipher.getBlockSize() + ", symm key length: " + keyBytes.length);
    }
    int blockSize = cipher.getBlockSize();
    if (blockSize > 0 && blockSize < keyBytes.length) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyTransp",
                new Object[] { "public key algorithm too weak to encrypt symmetric key" });
    }

    try {
        this.encryptedEphemeralKey = cipher.doFinal(keyBytes);
    } catch (IllegalStateException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    } catch (IllegalBlockSizeException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    } catch (BadPaddingException e1) {
        throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1);
    }
    Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document, this.encryptedEphemeralKey);

    //
    // Now we need to setup the EncryptedKey header block 1) create a
    // EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
    // element, this wraps the wsse:SecurityTokenReference 3) Create and set
    // up the SecurityTokenReference according to the keyIdentifier parameter
    // 4) Create the CipherValue element structure and insert the encrypted
    // session key
    //
    encryptedKeyElement = createEncryptedKey(document, keyEncAlgo);
    if (this.encKeyId == null || "".equals(this.encKeyId)) {
        this.encKeyId = "EncKeyId-" + UUIDGenerator.getUUID();
    }
    encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId);

    KeyInfo keyInfo = new KeyInfo(document);

    SecurityTokenReference secToken = new SecurityTokenReference(document);

    switch (keyIdentifierType) {
    case WSConstants.X509_KEY_IDENTIFIER:
        secToken.setKeyIdentifier(remoteCert);
        break;

    case WSConstants.SKI_KEY_IDENTIFIER:
        secToken.setKeyIdentifierSKI(remoteCert, crypto);
        break;

    case WSConstants.THUMBPRINT_IDENTIFIER:
        secToken.setKeyIdentifierThumb(remoteCert);
        break;

    case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
        //
        // This identifier is not applicable for this case, so fall back to
        // ThumbprintRSA.
        //
        secToken.setKeyIdentifierThumb(remoteCert);
        break;

    case WSConstants.ISSUER_SERIAL:
        XMLX509IssuerSerial data = new XMLX509IssuerSerial(document, remoteCert);
        X509Data x509Data = new X509Data(document);
        x509Data.add(data);
        secToken.setX509IssuerSerial(x509Data);
        break;

    case WSConstants.BST_DIRECT_REFERENCE:
        Reference ref = new Reference(document);
        ref.setURI("#" + certUri);
        bstToken = new X509Security(document);
        ((X509Security) bstToken).setX509Certificate(remoteCert);
        bstToken.setID(certUri);
        ref.setValueType(bstToken.getValueType());
        secToken.setReference(ref);
        break;

    case WSConstants.CUSTOM_KEY_IDENTIFIER:
        secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId);
        break;

    default:
        throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
    }
    keyInfo.addUnknownElement(secToken.getElement());
    Element keyInfoElement = keyInfo.getElement();
    keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS);
    encryptedKeyElement.appendChild(keyInfoElement);

    Element xencCipherValue = createCipherValue(document, encryptedKeyElement);
    xencCipherValue.appendChild(keyText);

    envelope = document.getDocumentElement();
    envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
}

From source file:acp.sdk.SecureUtil.java

/**
 * //from  www  . j a v  a 2 s . co m
 * @param publicKey
 * @param plainData
 * @return
 * @throws Exception
 */
public byte[] encryptedData(PublicKey publicKey, byte[] plainData) throws Exception {
    try {
        //         Cipher cipher = CliperInstance.getInstance();
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int blockSize = cipher.getBlockSize();
        int outputSize = cipher.getOutputSize(plainData.length);
        int leavedSize = plainData.length % blockSize;
        int blocksSize = leavedSize != 0 ? plainData.length / blockSize + 1 : plainData.length / blockSize;
        byte[] raw = new byte[outputSize * blocksSize];
        int i = 0;
        while (plainData.length - i * blockSize > 0) {
            if (plainData.length - i * blockSize > blockSize) {
                cipher.doFinal(plainData, i * blockSize, blockSize, raw, i * outputSize);
            } else {
                cipher.doFinal(plainData, i * blockSize, plainData.length - i * blockSize, raw, i * outputSize);
            }
            i++;
        }
        return raw;
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }
}

From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java

@Override
public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException {
    // derive our decryption and hmac keys as per RFC 3961
    // first work out the "well known constant"s for the different keys
    byte[] wkcKe = new byte[5];
    wkcKe[0] = (byte) ((keyUsage >> 24) & 0xFF);
    wkcKe[1] = (byte) ((keyUsage >> 16) & 0xFF);
    wkcKe[2] = (byte) ((keyUsage >> 8) & 0xFF);
    wkcKe[3] = (byte) (keyUsage & 0xFF);
    wkcKe[4] = (byte) 0xAA;
    byte[] wkcKi = (byte[]) wkcKe.clone();
    wkcKi[4] = (byte) 0x55;

    // then make the keys
    // RFC 3961: Derived Key = DK(Base Key, Well-Known Constant)
    SecretKey ke = new SecretKeySpec(dk(key.getEncoded(), wkcKe), "DESede");
    SecretKey ki = new SecretKeySpec(dk(key.getEncoded(), wkcKi), "DESede");

    // set up the HMAC object so we can get the length
    Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
    hmacSHA1.init(ki);/*from  w w w .  ja va  2s.c  o m*/
    int hmacLength = hmacSHA1.getMacLength();

    // first split the checksum off the data
    InputStream is = new ByteArrayInputStream(cipherData);
    byte[] data = new byte[cipherData.length - hmacLength];
    if (is.read(data) != data.length) {
        throw new IOException("Couldn't read all the encrypted data.");
    }
    byte[] checksum = new byte[hmacLength];
    if (is.read(checksum) != checksum.length) {
        throw new IOException("Couldn't read all the checksum data.");
    }

    // then decrypt the data
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    cipher.init(DECRYPT_MODE, ke, IV);
    byte[] decrypted = cipher.doFinal(data);

    // check the HMAC
    byte[] newChecksum = hmacSHA1.doFinal(decrypted);
    if (!Arrays.equals(checksum, newChecksum)) {
        throw new GeneralSecurityException("Checksum failure.");
        //System.out.println("Checksum failed.");
    }

    // throw away the confounder and then return an ASN.1 encodable object
    is = new ByteArrayInputStream(decrypted);
    is.skip(cipher.getBlockSize());
    ASN1InputStream ais = new ASN1InputStream(is);
    return (ASN1Encodable) ais.readObject();
}