Example usage for javax.crypto Cipher doFinal

List of usage examples for javax.crypto Cipher doFinal

Introduction

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

Prototype

public final byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException 

Source Link

Document

Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation.

Usage

From source file:com.liusoft.dlog4j.upgrade.StringUtils.java

/**
 * //ww w . j a va 2 s .  co  m
 * @param src ??
 * @param key 8?
 * @return     ??
 * @throws Exception
 */
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
    //      DES????
    SecureRandom sr = new SecureRandom();
    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(key);
    // ?DESKeySpec??
    // SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher??
    Cipher cipher = Cipher.getInstance(DES);
    // ?Cipher
    cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    // ??
    // ??
    return cipher.doFinal(src);
}

From source file:com.liusoft.dlog4j.upgrade.StringUtils.java

/**
 * /* w w w.  ja  v  a2  s  . co m*/
 * @param src   ??
 * @param key   8?
 * @return      ??
 * @throws Exception
 */
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
    //      DES????
    SecureRandom sr = new SecureRandom();
    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(key);
    // ?DESKeySpec??
    // SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher??
    Cipher cipher = Cipher.getInstance(DES);
    // ?Cipher
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    // ??
    // ??
    return cipher.doFinal(src);
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * //w  w  w. j a  va  2  s .c o m
 *
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

    // ?
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static Certificate signCertificate(Certificate issuer, PrivateKey issuerPrivateKey,
        Certificate certificate) {
    if (issuer.getSerialNumber() != certificate.getIssuer()) {
        throw new CertificateIssuerMismatchException(
                "The authority certificate serial number doesn't much the certificate issuer.");
    }//ww  w.j a  va2  s  . c  om
    validatePermissions(issuer, certificate);
    final byte[] hash = certificate.hash();

    try {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, issuerPrivateKey);
        final byte[] signature = cipher.doFinal(hash);
        return new Certificate(certificate.getType(), certificate.getSerialNumber(), certificate.getIssuer(),
                certificate.getExpirationDate(), certificate.getPublicKey(),
                certificate.getSubscribePermissions(), certificate.getPublishPermissions(),
                certificate.getComment(), signature);
    } catch (GeneralSecurityException e) {
        throw new CertificateSecurityException(e);
    }
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *//*ww  w . j  a  v a2 s  .  com*/
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * /*from ww  w . ja  v a2  s  . co m*/
 *
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {

    // ?
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ?
    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?/*from www . j  a  v a 2 s.c  o  m*/
 *
 * @param data
 *            ?
 * @param key
 *            ?
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {

    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?/* www .jav a  2s. c  om*/
 *
 * @param data
 *            ?
 * @param key
 *            ?
 * @return byte[] ?
 * @throws Exception
 */
private static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {

    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

    cipher.init(Cipher.ENCRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}

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

public static String decrypt(byte[] key, String ciphertext)
        throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    if (!ciphertext.startsWith(FWKNOP_ENCRYPTION_HEADER)) {
        ciphertext = FWKNOP_ENCRYPTION_HEADER.concat(ciphertext);
    }//from  w  w  w  . j  a  va  2s  . co m
    // we need to remove Salted__ from the salt_and_ciphertext therefore -> SALT_LEN +/- 8

    byte[] salt_and_ciphertext = Base64.decodeBase64(ciphertext);
    byte[] salt = new byte[SALT_LEN];
    byte[] cipher = new byte[salt_and_ciphertext.length - SALT_LEN - 8];
    System.arraycopy(salt_and_ciphertext, 8, salt, 0, SALT_LEN);
    System.arraycopy(salt_and_ciphertext, 8 + SALT_LEN, cipher, 0, cipher.length);
    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.DECRYPT_MODE, enc_key, iv);
    byte[] plain = aes.doFinal(cipher);

    return new String(plain, "UTF-8");
}

From source file:ec.edu.uce.medicina.seguimiento.util.EncryptionUtility.java

/**
 *Mtodo que permite la desencriptacin de la contrasea
 * @param encrypted/*from w  w w .ja va 2 s . c o m*/
 * @return
 * @throws Exception
 */
public static String decrypt(String encrypted) throws Exception {
    String key = "02AE31B79CCCB2A3"; //llave
    String iv = "0123456789ABCDEF";
    Cipher cipher = Cipher.getInstance(cI);
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), alg);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
    byte[] enc = decodeBase64(encrypted);
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decrypted = cipher.doFinal(enc);
    return new String(decrypted);
}