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.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * /*  w  ww  .j  a v a2  s.  c  o m*/
 * 
 * 
 * @param info ?
 * @return ?
 * @throws GeneralSecurityException GeneralSecurityException
 */
public String encode(String info) throws GeneralSecurityException {
    // ?token?
    byte[] pubKeyText = this.getPubKeyText();
    X509EncodedKeySpec bobPKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKeyText));
    KeyFactory keyFactory = null;
    if (provider == null) {
        keyFactory = KeyFactory.getInstance(ALGORITHM);
    } else {
        keyFactory = KeyFactory.getInstance(ALGORITHM, provider);
    }
    // ?
    PublicKey pubkey = keyFactory.generatePublic(bobPKeySpec);
    // CipherECB?PKCS5Padding
    Cipher cipher = null;
    if (provider == null) {
        cipher = Cipher.getInstance(ALGORITHM);
    } else {
        cipher = Cipher.getInstance(ALGORITHM, provider);
    }
    // ?
    cipher.init(Cipher.ENCRYPT_MODE, pubkey);
    byte[] cipherText = cipher.doFinal(info.getBytes());
    return new String(Base64.encodeBase64(cipherText));
}

From source file:com.github.aelstad.keccakj.keyak.KeyakTestUtils.java

public void runTests(List<KeyakTest> tests) throws Exception {
    LakeKeyak wrapper = new LakeKeyak();
    LakeKeyak unwrapper = new LakeKeyak();
    LakeKeyak unwrapperFailing = new LakeKeyak();

    for (KeyakTest dt : tests) {
        System.out.println("initialize with:");
        System.out.println("key: " + toHex(dt.key));
        System.out.println("nonce: " + toHex(dt.nonce));

        wrapper.init(dt.key, dt.nonce);/*from  w ww  . j  a  v  a2 s  . c o m*/
        unwrapper.init(dt.key, dt.nonce);
        unwrapperFailing.init(dt.key, dt.nonce);

        LakeKeyakCipher lkEncryptingCipher = new LakeKeyakCipher();
        lkEncryptingCipher.init(Cipher.ENCRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        LakeKeyakCipher lkDecryptingCipher = new LakeKeyakCipher();
        lkDecryptingCipher.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        LakeKeyakCipher lkDecryptingFailing = new LakeKeyakCipher();
        lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce));

        for (TestCommand tc : dt.commands) {
            if (tc instanceof ForgetCommand) {
                System.out.println("forget");
                lkEncryptingCipher.forget();
                lkDecryptingCipher.forget();
            } else if (tc instanceof PairCommand) {
                PairCommand pc = (PairCommand) tc;
                System.out.println("associated data: " + toHex(pc.ad));
                System.out.println("plaintext: " + toHex(pc.plaintext));
                System.out.println("ciphertext: " + toHex(pc.ciphertext));
                System.out.println("tag: " + toHex(pc.tag));

                byte[] wrapOut = new byte[pc.plaintext.length];
                byte[] tagOut = new byte[pc.tag.length];

                lkEncryptingCipher.updateAAD(pc.ad);
                byte[] encrypted = lkEncryptingCipher.doFinal(pc.plaintext);
                Assert.assertTrue(encrypted.length == pc.plaintext.length + 16);

                System.arraycopy(encrypted, 0, wrapOut, 0, pc.plaintext.length);
                System.arraycopy(encrypted, encrypted.length - 16, tagOut, 0, 16);

                System.out.println("got ciphertext: " + toHex(wrapOut));
                System.out.println("got tag: " + toHex(tagOut));

                Assert.assertArrayEquals(wrapOut, pc.ciphertext);
                Assert.assertArrayEquals(tagOut, pc.tag);

                lkDecryptingCipher.updateAAD(pc.ad);
                byte[] decrypted = lkDecryptingCipher.doFinal(encrypted);
                Assert.assertArrayEquals(decrypted, pc.plaintext);

                lkDecryptingFailing.updateAAD(pc.ad);
                AEADBadTagException expected = null;
                try {
                    byte[] decryptedFailing = lkDecryptingFailing.doFinal(new byte[16]);
                } catch (AEADBadTagException ex) {
                    expected = ex;
                }
                Assert.assertNotNull(expected);

                lkDecryptingFailing = new LakeKeyakCipher();
                lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key),
                        new IvParameterSpec(dt.nonce));

            }
            System.out.println();
        }

    }
}

From source file:edu.ku.brc.helpers.Encryption.java

/**
 * Encrypts the string from its array of bytes
 * @param input the actual string (in bytes) that is to be encrypted
 * @param password a password, which is really any string, but must be the same string that was used to decrypt it.
 * @return a byte array of the encrypted chars
 * @throws Exception in case something goes wrong
 *///from  w w  w . j a v  a2  s. co m
public static byte[] encrypt(byte[] input, char[] password) throws Exception {
    /*
     * Get ourselves a random number generator, needed in a number of places for encrypting.
     */
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$

    /*
     * A "salt" is considered an essential part of password-based encryption. The salt is
     * selected at random for each encryption. It is not considered "sensitive", so it is tacked
     * onto the generated ciphertext without any special processing. It doesn't matter if an
     * attacker actually gets the salt. The salt is used as part of the key, with the very
     * useful result that if you Encryption the same plaintext with the same password twice, you
     * get *different* ciphertexts. There are lots of pages on the 'net with information about
     * salts and password-based encryption, so read them if you want more details. Suffice to
     * say salt=good, no salt=bad.
     */
    byte[] salt = new byte[SALT_LENGTH];
    sr.nextBytes(salt);

    /*
     * We've now got enough information to build the actual key. We do this by encapsulating the
     * variables in a PBEKeySpec and using a SecretKeyFactory to transform the spec into a key.
     */
    PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey key = skf.generateSecret(keyspec);

    /*
     * We'll use a ByteArrayOutputStream to conveniently gather up data as it's encrypted.
     */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /*
     * We've to a key, but to actually Encryption something, we need a "cipher". The cipher is
     * created, then initialized with the key, salt, and iteration count. We use a
     * PBEParameterSpec to hold the salt and iteration count needed by the Cipher object.
     */
    PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key, paramspec, sr);

    /*
     * First, in our output, we need to save the salt in plain unencrypted form.
     */
    baos.write(salt);

    /*
     * Next, Encryption our plaintext using the Cipher object, and write it into our output buffer.
     */
    baos.write(cipher.doFinal(input));

    /*
     * We're done. For security reasons, we probably want the PBEKeySpec object to clear its
     * internal copy of the password, so it can't be stolen later.
     */
    keyspec.clearPassword();
    return baos.toByteArray();
}

From source file:eap.util.EDcodeUtil.java

public static String desEncodeAsHex(byte[] data, byte[] key) {
    return hexEncode(des(data, key, Cipher.ENCRYPT_MODE));
}

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

/**
 * Encrypts/decrypts a message using the underlying symmetric key and mode.
 *
 * @param message if in encryption mode, the clear-text message to encrypt,
 *        otherwise a base64 encoded version of the raw byte array
 *        containing the message to decrypt
 * @return if in encryption mode, returns a base64 encoded version of the
 *         encrypted message, otherwise returns the clear-text message
 * @throws SymmetricEncryptionException on runtime errors
 * @see #setMode(Mode)//w ww.  j av a 2s.  co  m
 */
public String encrypt(String message) {
    try {
        final Cipher cipher = (((provider == null) || (provider.length() == 0))
                ? Cipher.getInstance(cipherAlgorithm)
                : Cipher.getInstance(cipherAlgorithm, provider));
        switch (mode) {
        case ENCRYPT:
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
            byte[] encryptedMessage = cipher.doFinal(message.getBytes(charsetName));
            return new String(Base64.encodeBase64(encryptedMessage, chunkOutput));
        case DECRYPT:
            cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
            byte[] decodedMessage = Base64.decodeBase64(message);
            return new String(cipher.doFinal(decodedMessage), charsetName);
        default:
            return null;
        }
    } catch (Exception e) {
        throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:com.eucalyptus.crypto.StringCrypto.java

public byte[] encrypt(String password) throws GeneralSecurityException {
    Key pk = keystore.getCertificate(ALIAS).getPublicKey();
    Cipher cipher = Cipher.getInstance(this.asymmetricFormat, this.provider);
    cipher.init(Cipher.ENCRYPT_MODE, pk, Crypto.getSecureRandomSupplier().get());
    byte[] passwordEncrypted = cipher.doFinal(password.getBytes());
    return UrlBase64.encode(passwordEncrypted);
    //return cat (VMwareBrokerProperties.ENCRYPTION_FORMAT.getBytes(), UrlBase64.encode(passwordEncrypted)); // prepend format
}

From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java

@Test
public void shouldGenerateValidRSAKeyPair() throws Exception {
    String text = "this is a secret message";
    X509CertificateGenerator generator = new X509CertificateGenerator();
    Registration registration = generator.createAgentCertificate(keystore, "agentHostName");
    PrivateKey privateKey = registration.getPrivateKey();
    PublicKey publicKey = registration.getPublicKey();

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decrypted = cipher.doFinal(encrypted);
    assertThat(decrypted, is(text.getBytes()));
}

From source file:fi.elfcloud.sci.DataItem.java

/**
 * Stores data to {@link DataItem}//  ww  w  . j av a2 s .com
 * @param method the store method used for store operation (<code>new</code> or <code>replace</code>)
 * @param is the data to be sent
 * @throws IOException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws ECException
 * @throws ECEncryptionException
 */
public void storeData(String method, InputStream is) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, ECException, ECEncryptionException {
    Map<String, String> headers = new HashMap<String, String>();
    String meta = "";
    synchronized (this) {
        meta = this.client.createMeta(this.meta);
    }
    headers.put("X-ELFCLOUD-STORE-MODE", method);
    headers.put("X-ELFCLOUD-KEY", Base64.encodeBase64String(this.name.getBytes("UTF-8")));
    headers.put("X-ELFCLOUD-PARENT", Integer.toString(this.parentId));
    headers.put("X-ELFCLOUD-META", meta);
    headers.put("Content-Type", "application/octet-stream");
    MessageDigest ciphermd = null;
    MessageDigest plainmd = null;
    try {
        ciphermd = MessageDigest.getInstance("MD5");
        plainmd = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
    }

    DigestInputStream digestStream = new DigestInputStream(is, plainmd);
    InputStream dataStream;
    if (client.getEncryptionMode() != Client.ENC.NONE) {
        dataStream = new DataStream(Cipher.ENCRYPT_MODE, digestStream, null).getStream();
    } else {
        dataStream = new DataStream(0, digestStream, null).getStream();
    }

    int buffsize = 20971520;
    byte[] buff = new byte[buffsize];
    int len = 0;
    int inbuff = 0;
    while ((len = dataStream.read(buff, 0, buffsize)) > 0) {
        inbuff = len;
        while ((inbuff < buffsize)) {
            len = dataStream.read(buff, inbuff, buffsize - inbuff);
            if (len == -1) {
                break;
            }
            inbuff += len;
        }
        ciphermd.update(buff, 0, inbuff);
        headers.put("Content-Length", Integer.toString(inbuff));
        headers.put("X-ELFCLOUD-HASH", Utils.getHex(ciphermd.digest()));
        this.client.getConnection().sendData(headers, buff, inbuff);
        headers.put("X-ELFCLOUD-STORE-MODE", "append");
    }
    this.meta = meta;
    HashMap<String, String> metamap = Utils.metaToMap(this.meta);
    metamap.put("CHA", Utils.getHex(plainmd.digest()));
    updateMeta(metamap);
}

From source file:de.alpharogroup.crypto.aes.HexEncryptor.java

/**
 * Initializes the {@link HexEncryptor} object.
 *
 * @throws UnsupportedEncodingException//from  w w w . ja  v  a  2s. co m
 *             is thrown by get the byte array of the private key String object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws NoSuchPaddingException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeyException
 *             the invalid key exception is thrown if initialization of the cypher object fails.
 */
private void initialize() throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException {
    if (!isInitialized()) {
        byte[] key;
        if (this.getPrivateKey() != null) {
            key = this.getPrivateKey().getBytes("UTF-8");
        } else {
            key = CryptConst.PRIVATE_KEY.getBytes("UTF-8");
        }
        final SecretKeySpec skeySpec = new SecretKeySpec(key, algorithm.getAlgorithm());
        this.cipher = Cipher.getInstance(algorithm.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    }
}

From source file:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @param plaintextedPassword//from w  w w . j a v  a 2  s  . c  o m
 * @return encrpytedPassword
 * @throws IOException 
 * @throws InvalidKeySpecException 
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeyException 
 * @throws BadPaddingException 
 * @throws IllegalBlockSizeException 
 */
public STAFResult getEncryptedPassword(String plaintextedPassword)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {
    String encryptedPassword = null;

    RSAPublicKey publicKey = getPublicKey();

    this.cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] raw = plaintextedPassword.getBytes();

    // encrypt the message
    byte[] passBytes = this.cipher.doFinal(raw);

    // encode the encrypted message as base64
    encryptedPassword = Base64.encodeBase64String(passBytes);

    //omits CRLF
    encryptedPassword = encryptedPassword.replace("\r\n", "");

    return new STAFResult(STAFResult.Ok, encryptedPassword);
}