Example usage for javax.crypto Cipher init

List of usage examples for javax.crypto Cipher init

Introduction

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

Prototype

public final void init(int opmode, Certificate certificate) throws InvalidKeyException 

Source Link

Document

Initializes this cipher with the public key from the given certificate.

Usage

From source file:io.zipi.common.util.AesEncrypter.java

/**
 * Encrypt./*w w  w.  j  a  va2  s. c  o  m*/
 * @param plainText the plain text
 * @param secretKey the secret key
 * @return the string
 */
public static String encrypt(String secretKey, String plainText) {
    if (plainText == null) {
        return null;
    }
    byte[] encrypted;
    Cipher cipher;
    try {
        SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);

        cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }
    try {
        encrypted = cipher.doFinal(plainText.getBytes());
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        throw new RuntimeException(e);
    }
    return "$CRYPT::" + new String(Base64.encodeBase64(encrypted)); //$NON-NLS-1$
}

From source file:hudson.util.Secret.java

/**
 * Reverse operation of {@link #getEncryptedValue()}. Returns null
 * if the given cipher text was invalid.
 *//*from w  w w .j  ava 2 s . c  o  m*/
public static Secret decrypt(String data) {
    if (data == null)
        return null;
    try {
        byte[] in = Base64.decode(data.toCharArray());
        Secret s = tryDecrypt(KEY.decrypt(), in);
        if (s != null)
            return s;

        // try our historical key for backward compatibility
        Cipher cipher = getCipher("AES");
        cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());
        return tryDecrypt(cipher, in);
    } catch (GeneralSecurityException e) {
        return null;
    } catch (UnsupportedEncodingException e) {
        throw new Error(e); // impossible
    } catch (IOException e) {
        return null;
    }
}

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.");
    }/*w ww.ja  v  a2  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:cloudeventbus.pki.CertificateUtils.java

public static void validateSignature(PublicKey key, byte[] challenge, byte[] salt, byte[] signature) {
    try {// ww  w  .j  ava 2 s .  c  om
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        final byte[] decryptedSignature = cipher.doFinal(signature);
        if (decryptedSignature.length != challenge.length + salt.length) {
            throw new InvalidSignatureException("Signature doesn't match challenge");
        }
        for (int i = 0; i < challenge.length; i++) {
            if (decryptedSignature[i] != challenge[i]) {
                throw new InvalidSignatureException("Signature doesn't match challenge");
            }
        }
        for (int i = 0; i < salt.length; i++) {
            if (decryptedSignature[challenge.length + i] != salt[i]) {
                throw new InvalidSignatureException("Signature doesn't match challenge");
            }
        }
    } catch (GeneralSecurityException e) {
        throw new CertificateSecurityException(e);
    }
}

From source file:com.shenit.commons.codec.RsaUtils.java

/**
 * //w  ww .  j a  va 2 s .c o m
 * 
 * @param content
 *            
 * @param privateKey
 *            ?
 * @param inputCharset
 *            ??
 * @return ?
 */
public static String decrypt(String content, String privateKey, String inputCharset) {
    InputStream ins = null;
    ByteArrayOutputStream writer = null;
    String result = null;
    try {
        PrivateKey prikey = getPrivateKey(privateKey);

        Cipher cipher = Cipher.getInstance(CODEC_RSA);
        cipher.init(Cipher.DECRYPT_MODE, prikey);

        ins = new ByteArrayInputStream(Base64.decodeBase64(content));
        writer = new ByteArrayOutputStream();
        // rsa?128?128?
        byte[] buf = new byte[128];
        int bufl;

        while ((bufl = ins.read(buf)) != -1) {
            byte[] block = null;

            if (buf.length == bufl) {
                block = buf;
            } else {
                block = new byte[bufl];
                for (int i = 0; i < bufl; i++) {
                    block[i] = buf[i];
                }
            }

            writer.write(cipher.doFinal(block));
        }
        result = new String(writer.toByteArray(), inputCharset);
    } catch (Exception ex) {
        if (LOG.isWarnEnabled())
            LOG.warn("[decrypt] Decrypt failed with exception.", ex);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(ins);
    }

    return result;
}

From source file:Main.java

public static byte[] encryptMsg(String msg, RSAPublicKeySpec pubKeySpec) {
    if (msg != null && pubKeySpec != null && !msg.isEmpty()) {
        try {//from w ww . j a  v  a2 s.  com
            Log.w(TAG, "msg is: " + msg + " with length " + msg.length());
            KeyFactory fact = KeyFactory.getInstance("RSA");

            PublicKey pubKey = fact.generatePublic(pubKeySpec);

            // TODO encrypt the message and send it
            // Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // Cipher cipher =
            // Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding",
            // "BC");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            Log.d(TAG, "cipher block size is " + cipher.getBlockSize());
            byte[] msgByteArray = msg.getBytes();
            byte[] cipherData = new byte[cipher.getOutputSize(msgByteArray.length)];
            cipherData = cipher.doFinal(msgByteArray);
            Log.d(TAG, "output size is " + cipher.getOutputSize(msgByteArray.length));
            Log.d(TAG, "is the measurement already broken into chunks here? " + (new String(cipherData)));
            return cipherData;

        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "RSA algorithm not available", e);
        } catch (InvalidKeySpecException e) {
            Log.e(TAG, "", e);
        } catch (NoSuchPaddingException e) {
            Log.e(TAG, "", e);
        } catch (InvalidKeyException e) {
            Log.e(TAG, "", e);
        } catch (BadPaddingException e) {
            Log.e(TAG, "", e);
        } catch (IllegalBlockSizeException e) {
            Log.e(TAG, "", e);
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } /*
           * catch (NoSuchProviderException e) { Log.e(TAG, "", e); }
           */
    }
    return null;
}

From source file:com.cherong.mock.common.base.util.EncryptionUtil.java

/**
 * deskey//www  . ja  v a  2  s  .c  om
 * 
 * @param content
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByDES(String content, String key) {
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey sk = skf.generateSecret(dks);
        Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM);
        cip.init(Cipher.ENCRYPT_MODE, sk);
        return cip.doFinal(content.getBytes());
    } catch (Exception e) {
        LOGGER.error("{}", e);
        return null;
    }

}

From source file:com.cherong.mock.common.base.util.EncryptionUtil.java

/**
 * des/*from w  ww . j a v a 2s  .  co m*/
 * 
 * @param content
 * @param key
 * @return
 * @throws Exception
 */
public static String decryptByDES(byte[] content, String key) {
    try {
        DESKeySpec desKS = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey sk = skf.generateSecret(desKS);
        Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM);
        cip.init(Cipher.DECRYPT_MODE, sk);
        byte[] result = cip.doFinal(content);
        return new String(result);
    } catch (Exception e) {
        LOGGER.error("{}", e);
        return null;
    }
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * /*  ww w.  jav a 2 s.  c  o m*/
 * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
public static String encryptAESPBKDF2(String plainText) throws Exception {

    // get salt
    salt = generateSaltAESPBKDF2();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // encrypt the message
    Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:io.apiman.common.util.AesEncrypter.java

/**
 * Encrypt./*from  ww  w  .j  a  va 2  s  .  c  o m*/
 * @param plainText the plain text
 * @param secretKey the secret key
 * @return the string
 */
public static String encrypt(String secretKey, String plainText) {
    if (plainText == null) {
        return null;
    }
    byte[] encrypted;
    Cipher cipher;
    try {
        SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);

        cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }
    try {
        encrypted = cipher.doFinal(plainText.getBytes());
    } catch (IllegalBlockSizeException e) {
        throw new RuntimeException(e);
    } catch (BadPaddingException e) {
        throw new RuntimeException(e);
    }
    return "$CRYPT::" + new String(Base64.encodeBase64(encrypted)); //$NON-NLS-1$
}