Example usage for javax.crypto Cipher ENCRYPT_MODE

List of usage examples for javax.crypto Cipher ENCRYPT_MODE

Introduction

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

Prototype

int ENCRYPT_MODE

To view the source code for javax.crypto Cipher ENCRYPT_MODE.

Click Source Link

Document

Constant used to initialize cipher to encryption mode.

Usage

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * <p>cipher</p>/*from  w w w . j a va 2  s  .  c  om*/
 *
 * @param plainText an array of byte.
 * @return an array of byte.
 *
 * @throws GeneralSecurityException
 *          if any.
 */
@Nonnull
public byte[] cipher(@Nonnull byte[] plainText) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(RSA);
    cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey());
    return cipher.doFinal(plainText);
}

From source file:com.fujitsu.dc.common.auth.token.LocalToken.java

/**
 * ??./*  w ww.  j  a  v  a2 s  .c o  m*/
 * @param in 
 * @param ivBytes 
 * @return ???
 */
public static String encode(final String in, final byte[] ivBytes) {
    // IV??CELL?URL??????
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(ivBytes));
        byte[] cipherBytes = cipher.doFinal(in.getBytes(CharEncoding.UTF_8));
        return DcCoreUtils.encodeBase64Url(cipherBytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:io.personium.common.auth.token.LocalToken.java

/**
 * ??.//from   w  ww .  j  av  a 2  s.  co m
 * @param in 
 * @param ivBytes 
 * @return ???
 */
public static String encode(final String in, final byte[] ivBytes) {
    // IV??CELL?URL??????
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(ivBytes));
        byte[] cipherBytes = cipher.doFinal(in.getBytes(CharEncoding.UTF_8));
        return PersoniumCoreUtils.encodeBase64Url(cipherBytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:net.seleucus.wsp.crypto.FwknopSymmetricCrypto.java

public static String encrypt(byte[] key, String message)
        throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom sr = new SecureRandom();
    byte[] salt = new byte[8];
    sr.nextBytes(salt);//from  w  w  w.j a  v  a2s  .c o  m

    byte[][] key_and_iv = deriveKeyAndIV(salt, key);

    SecretKeySpec enc_key;
    enc_key = new SecretKeySpec(key_and_iv[0], "AES");
    Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec iv = new IvParameterSpec(key_and_iv[1]);
    aes.init(Cipher.ENCRYPT_MODE, enc_key, iv);

    byte[] salted = "Salted__".getBytes("UTF-8");
    byte[] cipher = aes.doFinal(message.getBytes("UTF-8"));

    byte[] result = new byte[salted.length + salt.length + cipher.length];

    // now we need to glue: "Salted__" + salt + cipher
    System.arraycopy(salted, 0, result, 0, salted.length);
    System.arraycopy(salt, 0, result, salted.length, salt.length);
    System.arraycopy(cipher, 0, result, salted.length + salt.length, cipher.length);

    // remove = and FWKNOP_ENCRYPTION_HEADER
    return Base64.encodeBase64String(result).replace("=", "").replace(FWKNOP_ENCRYPTION_HEADER, "");
}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java

public void canDoMultipartUpload() throws Exception {
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-my-key", "my value");
    metadata.put("e-my-key-1", "my value 1");
    metadata.put("e-my-key-2", "my value 2");

    MantaHttpHeaders headers = new MantaHttpHeaders();

    String path = "/user/stor/testobject";

    EncryptedMultipartUpload<TestMultipartUpload> upload = manager.initiateUpload(path, 35L, metadata, headers);

    ArrayList<String> lines = new ArrayList<>();
    lines.add("01234567890ABCDEF|}{");
    lines.add("ZYXWVUTSRQPONMLKJIHG");
    lines.add("!@#$%^&*()_+-=[]/,.<");
    lines.add(">~`?abcdefghijklmnop");
    lines.add("qrstuvxyz");

    String expected = StringUtils.join(lines, "");

    MantaMultipartUploadPart[] parts = new MantaMultipartUploadPart[5];

    for (int i = 0; i < lines.size(); i++) {
        parts[i] = manager.uploadPart(upload, i + 1, lines.get(i));
    }//from  w w  w  . j  a  va  2s  .  c om

    Stream<MantaMultipartUploadTuple> partsStream = Stream.of(parts);

    manager.complete(upload, partsStream);

    TestMultipartUpload actualUpload = upload.getWrapped();

    MantaMetadata actualMetadata = MantaObjectMapper.INSTANCE.readValue(actualUpload.getMetadata(),
            MantaMetadata.class);

    Assert.assertEquals(actualMetadata, metadata, "Metadata wasn't stored correctly");

    MantaHttpHeaders actualHeaders = MantaObjectMapper.INSTANCE.readValue(actualUpload.getHeaders(),
            MantaHttpHeaders.class);

    Assert.assertEquals(actualHeaders, headers, "Headers were stored correctly");

    {
        Cipher cipher = cipherDetails.getCipher();
        byte[] iv = upload.getEncryptionState().getEncryptionContext().getCipher().getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        byte[] assumedCiphertext = cipher.doFinal(expected.getBytes(StandardCharsets.US_ASCII));
        byte[] contents = FileUtils.readFileToByteArray(upload.getWrapped().getContents());
        byte[] actualCiphertext = Arrays.copyOf(contents,
                contents.length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());

        try {
            AssertJUnit.assertEquals(assumedCiphertext, actualCiphertext);
        } catch (AssertionError e) {
            System.err.println("expected: " + Hex.encodeHexString(assumedCiphertext));
            System.err.println("actual  : " + Hex.encodeHexString(actualCiphertext));
            throw e;
        }
    }

    EncryptionContext encryptionContext = upload.getEncryptionState().getEncryptionContext();

    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength(actualUpload.getContents().length());

    final String hmacName = SupportedHmacsLookupMap
            .hmacNameFromInstance(encryptionContext.getCipherDetails().getAuthenticationHmac());

    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV,
            Base64.getEncoder().encodeToString(encryptionContext.getCipher().getIV()));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    MantaObjectResponse response = new MantaObjectResponse(path, responseHttpHeaders, metadata);

    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

    try (InputStream fin = new FileInputStream(actualUpload.getContents());
            EofSensorInputStream eofIn = new EofSensorInputStream(fin, null);
            MantaObjectInputStream objIn = new MantaObjectInputStream(response, httpResponse, eofIn);
            InputStream in = new MantaEncryptedObjectInputStream(objIn, cipherDetails, secretKey, true)) {
        String actual = IOUtils.toString(in, StandardCharsets.UTF_8);

        Assert.assertEquals(actual, expected);
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.EncryptingContentWriterDecorator.java

public OutputStream getContentOutputStream() throws ContentIOException {
    logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] BEGIN");

    IvParameterSpec iv = null;//from   ww  w.ja  v  a  2  s.c om

    try {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec),
                    "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn(
                    "[EncryptingContentWriterDecorator::getContentOutputStream] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec));
        }

        if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) {
            iv = new IvParameterSpec(transformationSpec.getIv());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }

        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] "
                + "Cipher initialized: ENCRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm());

        CipherOutputStream cos = new CipherOutputStream(writer.getContentOutputStream(), cipher);

        return cos;
    } catch (NoSuchPaddingException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid padding: "
                + transformationSpec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm: "
                + transformationSpec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } catch (InvalidAlgorithmParameterException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm parameter: "
                + iv);
        throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e);
    } finally {
        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] END");
    }
}

From source file:com.springcryptoutils.core.cipher.symmetric.Base64EncodedCiphererImpl.java

/**
 * Encrypts or decrypts a message. The encryption/decryption mode depends on
 * the configuration of the mode parameter.
 *
 * @param key a base64 encoded version of the symmetric key
 * @param initializationVector a base64 encoded version of the
 *        initialization vector//  ww w.  j ava2s  .  c om
 * @param message if in encryption mode, the clear-text message to encrypt,
 *        otherwise a base64 encoded version of the message to decrypt
 * @return if in encryption mode, returns a base64 encoded version of the
 *         encrypted message, otherwise returns the decrypted clear-text
 *         message
 * @throws SymmetricEncryptionException on runtime errors
 * @see #setMode(com.google.code.springcryptoutils.core.cipher.Mode)
 */
public String encrypt(String key, String initializationVector, String message) {
    try {
        IvParameterSpec initializationVectorSpec = new IvParameterSpec(
                Base64.decodeBase64(initializationVector));
        final SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key), keyAlgorithm);
        final Cipher cipher = (((provider == null) || (provider.length() == 0))
                ? Cipher.getInstance(cipherAlgorithm)
                : Cipher.getInstance(cipherAlgorithm, provider));
        byte[] messageAsByteArray;

        switch (mode) {
        case ENCRYPT:
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = message.getBytes(charsetName);
            final byte[] encryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(Base64.encodeBase64(encryptedMessage, chunkOutput));
        case DECRYPT:
            cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = Base64.decodeBase64(message);
            final byte[] decryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(decryptedMessage, charsetName);
        default:
            return null;
        }
    } catch (Exception e) {
        throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:com.alkacon.opencms.commons.CmsStringCrypter.java

/**
 * Encrypts the given value.<p>//from w w  w .ja va2 s  .c om
 * 
 * @param value the string which should be encrypted
 * @param password the passsword used for encryption, use the same password for decryption
 * @return the encrypted string of the value or null if something went wrong
 */
public static String encrypt(String value, String password) {

    // check if given value is valid
    if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_WARN_INVALID_ENCRYPT_STRING_1, value));
        }
        return null;
    }

    try {

        // create key
        byte[] k = getKey(password);
        Key key = new SecretKeySpec(k, ENCRYPTION);
        Cipher cipher = Cipher.getInstance(ENCRYPTION);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        // encrypt text
        byte[] cleartext = value.getBytes(FORMAT);
        byte[] ciphertext = cipher.doFinal(cleartext);

        // encode with base64 to be used as a url parameter
        BASE64Encoder base64encoder = new BASE64Encoder();
        return CmsEncoder.encode(base64encoder.encode(ciphertext));
    } catch (Exception ex) {
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_ENCRYPT_0), ex);
        }
    }

    return null;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.Cipherer.java

/**
* Initializes the encoder and decoder. //from w  ww.j  a  v  a2 s .  c o m
* Note: The vaues of CIPHER_TRANSFORMATION, KEY_BYTES, KEY_ALGORITHM should be set before calling this method,
*       otherwise it will use the default values.
*/
public void init() {
    try {
        /*
                 byte[] nonce = new byte[16];
                 NONCE_GEN.nextBytes(nonce);
                 AlgorithmParameterSpec paramSpec = new IvParameterSpec(nonce);
        */
        AlgorithmParameterSpec paramSpec = cipherTransformation.toUpperCase().startsWith("AES")
                ? new IvParameterSpec(INIT_VECTOR_16)
                : new IvParameterSpec(INIT_VECTOR_8);

        E_CIPHER = Cipher.getInstance(cipherTransformation);
        D_CIPHER = Cipher.getInstance(cipherTransformation);

        SecretKeySpec spec = new SecretKeySpec(keyBytes, keyAlgorithm);

        // CBC requires an initialization vector
        E_CIPHER.init(Cipher.ENCRYPT_MODE, spec, paramSpec);
        D_CIPHER.init(Cipher.DECRYPT_MODE, spec, paramSpec);
    } catch (Exception e) {
        log.error("Cipher init failed", e);
        throw new RuntimeException(e);
    }
}

From source file:Crypto.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created 
 * along with the initialization vectory. The member variable mEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk.// www . ja v a2 s .  co m
 *  
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    mSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(mSalt);
    Db("generated salt :" + Hex.encodeHexString(mSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* Derive the key, given password and salt. 
     * 
     * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
     * The end user must also install them (not compiled in) so beware. 
     * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
     */
    KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    mEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = mEcipher.getParameters();

    // get the initialization vectory and store as member var 
    mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
}