List of usage examples for javax.crypto Cipher doFinal
public final byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException
From source file:de.extra.client.plugins.outputplugin.crypto.ExtraCryptoUtil.java
/** Encrypts the specified string, using the specified secret key. */ private static String encrypt(String sValue, String secretKey) { if (secretKey == null) { secretKey = SYM_KEY_STR;/*from w w w .j ava 2 s . com*/ } if (sValue == null || sValue.equals("")) { return ""; } String textEncode = null; Cipher encryptCipher = null; try { SecretKeySpec skeySpec = decodeKey(secretKey); encryptCipher = Cipher.getInstance(TRANSFORMATION); encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] plainText = sValue.trim().getBytes(CHARSET); // do the actual encryption byte[] cipherText = encryptCipher.doFinal(plainText); // Changed to encode() to avoid <cr> on end of string // textEncode = base64Encoder.encodeBuffer(cipherText); textEncode = new Base64().encodeAsString(cipherText); } catch (Exception e) { e.printStackTrace(System.err); } return textEncode; }
From source file:alfio.manager.CheckInManager.java
public static String encrypt(String key, String payload) { try {/*from www .ja v a 2 s. c o m*/ Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key); Cipher cipher = cipherAndSecret.getKey(); cipher.init(Cipher.ENCRYPT_MODE, cipherAndSecret.getRight()); byte[] data = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8)); byte[] iv = cipher.getIV(); return Base64.encodeBase64URLSafeString(iv) + "|" + Base64.encodeBase64URLSafeString(data); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
From source file:io.zipi.common.util.AesEncrypter.java
/** * Encrypt./*www .ja v a 2 s . co 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:com.mb.framework.util.SecurityUtil.java
/** * //from w w w . j ava 2s.c om * 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:com.github.woki.payments.adyen.action.CSEUtil.java
static String encrypt(final Cipher aesCipher, final Cipher rsaCipher, final String plainText) throws BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException { SecretKey aesKey = aesKey(256); byte[] iv = iv(CSE_RANDOM, 12); aesCipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv)); byte[] encrypted = aesCipher.doFinal(plainText.getBytes()); byte[] result = new byte[iv.length + encrypted.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(encrypted, 0, result, iv.length, encrypted.length); byte[] encryptedAESKey; try {/*from w w w.j a va2 s.c o m*/ encryptedAESKey = rsaCipher.doFinal(aesKey.getEncoded()); } catch (ArrayIndexOutOfBoundsException e) { throw new InvalidKeyException(e.getMessage()); } return String.format("%s%s%s%s%s%s", CSE_PREFIX, CSE_VERSION, CSE_SEPARATOR, Base64.encodeBase64String(encryptedAESKey), CSE_SEPARATOR, Base64.encodeBase64String(result)); }
From source file:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java
public static String getEncryptedKey(final String certArn, final String certPem) throws AuthException { final ServerCertificate targetCert = lookupServerCertificate(certArn); // generate symmetric key final MessageDigest digest = Digest.SHA256.get(); final byte[] salt = new byte[32]; Crypto.getSecureRandomSupplier().get().nextBytes(salt); digest.update(salt);//from w w w . j av a 2 s . c o m final SecretKey symmKey = new SecretKeySpec(digest.digest(), "AES"); try { // encrypt the server pk using symm key Cipher cipher = Ciphers.AES_CBC.get(); final byte[] iv = new byte[16]; Crypto.getSecureRandomSupplier().get().nextBytes(iv); cipher.init(Cipher.ENCRYPT_MODE, symmKey, new IvParameterSpec(iv), Crypto.getSecureRandomSupplier().get()); final byte[] cipherText = cipher.doFinal(Base64.encode(targetCert.getPrivateKey().getBytes())); final String encPrivKey = new String(Base64.encode(Arrays.concatenate(iv, cipherText))); // encrypt the symmetric key using the certPem X509Certificate x509Cert = PEMFiles.getCert(B64.standard.dec(certPem)); cipher = Ciphers.RSA_PKCS1.get(); cipher.init(Cipher.ENCRYPT_MODE, x509Cert.getPublicKey(), Crypto.getSecureRandomSupplier().get()); byte[] symmkey = cipher.doFinal(symmKey.getEncoded()); final String b64SymKey = new String(Base64.encode(symmkey)); return String.format("%s\n%s", b64SymKey, encPrivKey); } catch (final Exception ex) { throw Exceptions.toUndeclared(ex); } }
From source file:io.stallion.utils.Encrypter.java
public static String encryptString(String password, String value) { String salt = KeyGenerators.string().generateKey(); SecretKeySpec skeySpec = makeKeySpec(password, salt); byte[] iv = KeyGenerators.secureRandom(16).generateKey(); String ivString = Hex.encodeHexString(iv); try {// ww w. j a va 2 s.c om Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8"))); String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase(); // Strip line breaks s = salt + ivString + s.replaceAll("(\\n|\\r)", ""); return s; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java
public static String encrypt(String key, String toEncrypt) throws Exception { Key skeySpec = generateKeySpec(key); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider()); String abc = RandomStringUtils.randomAlphanumeric(16); System.out.println(abc);/* w w w .j a v a 2s . c o m*/ byte[] ivBytes = abc.getBytes(); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec); byte[] encrypted = cipher.doFinal(toEncrypt.getBytes()); byte[] encryptedValue; encryptedValue = Base64.encodeBase64(encrypted); String result = new String(); result += new String(encryptedValue); result = abc + result; System.out.println(result); return result; }
From source file:com.alkacon.opencms.commons.CmsStringCrypter.java
/** * Decrypts the given value which was encrypted with the encrypt method.<p> * /*from w ww. ja v a2 s . c o m*/ * @param value the value to be decrypted * @param password the passsword used for decryption, has to be the same as used for encryption * @return the decrypted string of the value or null if something went wrong */ public static String decrypt(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_DECRYPT_STRING_1, value)); } return null; } try { // create key Key key = new SecretKeySpec(getKey(password), ENCRYPTION); Cipher cipher = Cipher.getInstance(ENCRYPTION); cipher.init(Cipher.DECRYPT_MODE, key); // decode from base64 BASE64Decoder base64decoder = new BASE64Decoder(); byte[] cleartext = base64decoder.decodeBuffer(value); // decrypt text byte[] ciphertext = cipher.doFinal(cleartext); return CmsEncoder.decode(new String(ciphertext)); } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_DECRPYT_0), ex); } } return null; }
From source file:im.whistle.crypt.Crypt.java
/** * Encrypts a message./*from ww w .j a v a2 s. co m*/ * @param args Arguments: data, publicKey[, privateKey] * @param callback Callback */ public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { PRNGProvider.init(); // Ensure OpenSSL fix // Get the arguments String data = args.getString(0); String pub = args.getString(1); String priv = null; if (args.length() == 3) { priv = args.getString(2); } String sig = null; // Convert everything into byte arrays byte[] dataRaw = data.getBytes("utf-8"); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); // Generate random AES key and IV byte[] aesKey = new byte[AES_BYTES]; new SecureRandom().nextBytes(aesKey); byte[] aesIv = new byte[16]; // Block size new SecureRandom().nextBytes(aesIv); Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); // Encrypt data with AES byte[] encData = c.doFinal(dataRaw); // Encrypt aes data with RSA X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec)); c.update(aesKey); c.update(aesIv); byte[] encKey = c.doFinal(); // Concatenate and transform byte[] encRaw = new byte[encKey.length + encData.length]; System.arraycopy(encKey, 0, encRaw, 0, encKey.length); System.arraycopy(encData, 0, encRaw, encKey.length, encData.length); encKey = null; encData = null; String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8"); // Sign if (priv != null) { // Fail on error (no try-catch) byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initSign(kf.generatePrivate(privateKeySpec)); s.update(encRaw); sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8"); } JSONArray res = new JSONArray(); res.put(enc); res.put(sig); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex); callback.error(ex); } }