List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Decrypt a string value/*from w ww . jav a2 s . c o m*/ * * @param encryptedText the text String to be decrypted * @return the decrypted String * */ public static String decrypt(String encryptedText) { try { byte[] saltBytes = salt.getBytes("UTF-8"); byte[] encryptedTextBytes = Base64.decodeBase64(encryptedText); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); byte[] decryptedTextBytes = null; try { decryptedTextBytes = cipher.doFinal(encryptedTextBytes); } catch (IllegalBlockSizeException e) { logger.error("IllegalBlockSizeException when attempting to decrypt a string."); } catch (BadPaddingException e) { logger.error("BadPaddingException when attempting to decrypt a string."); } if (decryptedTextBytes != null) { return new String(decryptedTextBytes); } } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException when attempting to decrypt a string. "); } catch (InvalidKeySpecException e) { logger.error("InvalidKeySpecException when attempting to decrypt a string. "); } catch (NoSuchPaddingException e) { logger.error("NoSuchPaddingException when attempting to decrypt a string. "); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException when attempting to decrypt a string. "); } catch (InvalidKeyException e) { logger.error("InvalidKeyException when attempting to decrypt a string. "); } catch (InvalidAlgorithmParameterException e) { logger.error("InvalidAlgorithmParameterException when attempting to decrypt a string. "); } return null; }
From source file:tds.itemrenderer.security.Encryption.java
private synchronized String decrypt(final String stringToDecrypt) { try {// ww w.ja va 2s . c o m if (StringUtils.isEmpty(stringToDecrypt)) { return ""; } byte[] encryptedBytes = DatatypeConverter.parseBase64Binary(stringToDecrypt); byte[] iv = new byte[IV_LENGTH]; System.arraycopy(encryptedBytes, 0, iv, 0, iv.length); decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); byte[] cipherBytes = new byte[encryptedBytes.length - IV_LENGTH]; System.arraycopy(encryptedBytes, IV_LENGTH, cipherBytes, 0, cipherBytes.length); byte[] decryptedBytes = decryptCipher.doFinal(cipherBytes); return new String(decryptedBytes, UTF_8); } catch (InvalidAlgorithmParameterException e) { log.error("Encyption.decrypt: " + e.getMessage(), e); throw new TDSEncryptionException("Algorithm is not valid"); } catch (InvalidKeyException e) { log.error("Encyption.decrypt: " + e.getMessage(), e); throw new TDSEncryptionException("Key is not valid"); } catch (IllegalBlockSizeException e) { log.error("Encyption.decrypt: " + e.getMessage(), e); throw new TDSEncryptionException("Block size is not valid"); } catch (BadPaddingException e) { log.error("Encyption.decrypt: " + e.getMessage(), e); throw new TDSEncryptionException("Padding is not valid"); } }
From source file:com.orig.gls.security.Encode.java
public Encode(String keyString, String ivString) { try {/* w w w .j av a2s.c o m*/ final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8"))); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } keySpec = new DESedeKeySpec(keyBytes); key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec); iv = new IvParameterSpec(ivString.getBytes()); } catch (UnsupportedEncodingException asd) { System.out.println(asd.getMessage()); } catch (InvalidKeyException asd) { System.out.println(asd.getMessage()); } catch (NoSuchAlgorithmException asd) { System.out.println(asd.getMessage()); } catch (InvalidKeySpecException asd) { System.out.println(asd.getMessage()); } }
From source file:org.slc.sli.dal.encrypt.AesCipher.java
/** * Builds a new cipher that can be used independently of other threads. * // ww w . jav a 2 s. c o m * @param mode * @return */ protected Cipher buildCipher(int mode) { CipherInitData initData = initDataProvider.getInitData(); byte[] ivBytes; try { ivBytes = Hex.decodeHex(initData.getInitializationVector().toCharArray()); } catch (DecoderException e) { throw new RuntimeException(e); } IvParameterSpec ivspec = new IvParameterSpec(ivBytes); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, initData.getSecretKey(), ivspec); return cipher; } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
From source file:hudson.cli.Connection.java
/** * Upgrades a connection with transport encryption by the specified symmetric cipher. * * @return//from ww w. j a v a 2 s .c o m * A new {@link Connection} object that includes the transport encryption. */ public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException { Cipher cout = Cipher.getInstance(algorithm); cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherOutputStream o = new CipherOutputStream(out, cout); Cipher cin = Cipher.getInstance(algorithm); cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherInputStream i = new CipherInputStream(in, cin); return new Connection(i, o); }
From source file:com.ibasco.agql.examples.base.BaseExample.java
/** * @see <a href="https://gist.github.com/bricef/2436364">https://gist.github.com/bricef/2436364</a> *//* w w w . ja v a 2 s .c o m*/ public static String decrypt(String cipherText) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(worldsMostSecureUnhackableKey.getBytes("UTF-8"), "AES"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(worldsMostSecureUnhackableIvKey.getBytes("UTF-8"))); byte[] cipherBytes = Base64.getDecoder().decode(cipherText); return new String(cipher.doFinal(cipherBytes), "UTF-8"); }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * //w ww . ja v a 2s. c o m * Method that decrypts data * @param ciphertext byte array to decrypt * @return the decrypted string if decryption was successful, * null otherwise * */ public String decrypt(byte[] ciphertext) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption //iv is same as block size: for AES => 128 bits = 16 bytes byte[] iv = Arrays.copyOfRange(ciphertext, 0, 16); byte[] cipherText = Arrays.copyOfRange(ciphertext, 16, ciphertext.length); Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); String s = new String(cipher.doFinal(cipherText)); //Since this decryption was successful, it means we have the correct key, //so we can disable the count of failed decryptions countDecryptionFailed = false; return s; } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidKeyException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidAlgorithmParameterException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { Log.d(TAG, e.getMessage() + " "); countFailedDecryption(); e.printStackTrace(); return null; } catch (BadPaddingException e) { Log.d(TAG, e.getMessage() + " "); countFailedDecryption(); e.printStackTrace(); return null; } }
From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}/*from w ww . j a v a 2 s .co m*/ */ @Override public final byte[] desCbc(byte[] data, byte[] bKey, Mode mode) throws McbpCryptoException { try { SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(bKey)); final Cipher cipher = Cipher.getInstance("DES/CBC/noPadding"); final IvParameterSpec ips = new IvParameterSpec(new byte[8]); if (mode == Mode.ENCRYPT) { cipher.init(Cipher.ENCRYPT_MODE, key, ips); } else { cipher.init(Cipher.DECRYPT_MODE, key, ips); } return cipher.doFinal(data); } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { throw new McbpCryptoException(e.toString()); } }
From source file:Crypto.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * //w w w . ja v a2 s . com * @param initvec * @param salt * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException */ public void setupDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; // since we pass it as a string of input, convert to a actual byte buffer here mSalt = Hex.decodeHex(salt.toCharArray()); Db("got salt " + Hex.encodeHexString(mSalt)); // get initialization vector from passed string mInitVec = Hex.decodeHex(initvec.toCharArray()); Db("got initvector :" + Hex.encodeHexString(mInitVec)); /* 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 factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Decrypt the message, given derived key and initialization vector. */ mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec)); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
protected void doUpload() { DbAdapter dba = new DbAdapter(this); dba.open();//from ww w . j ava 2 s.c om Cursor allLogs = dba.fetchAll(); StringBuilder sb = new StringBuilder(); allLogs.moveToFirst(); sb.append("DateTime"); sb.append(","); sb.append("Process"); sb.append(","); sb.append("Type"); sb.append(","); sb.append("Component"); sb.append(","); sb.append("ActionString"); sb.append(","); sb.append("Category"); sb.append("\n"); while (!allLogs.isAfterLast()) { sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3))); sb.append(","); sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4))); sb.append("\n"); allLogs.moveToNext(); } dba.close(); File appDir = getDir("toUpload", MODE_PRIVATE); UUID uuid; uuid = MainScreen.getOrCreateUUID(this); long time = System.currentTimeMillis(); String basename = uuid.toString() + "_AT_" + time; String filename = basename + ".zip.enc"; File file = new File(appDir, filename); FileOutputStream out = null; ZipOutputStream outzip = null; CipherOutputStream outcipher = null; Cipher datac = null; File keyfile = new File(appDir, basename + ".key.enc"); //Log.i("sb length", Integer.toString(sb.length())); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String email = prefs.getString(MainScreen.EMAIL_KEY, ""); String emailFilename = "email.txt"; String csvFilename = "mouflon_log_" + time + ".csv"; try { SecretKey aeskey = generateAESKey(); //Log.i("secret key", bytearrToString(aeskey.getEncoded())); encryptAndWriteAESKey(aeskey, keyfile); datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); byte[] ivbytes = genIV(); IvParameterSpec iv = new IvParameterSpec(ivbytes); datac.init(Cipher.ENCRYPT_MODE, aeskey, iv); out = new FileOutputStream(file); out.write(ivbytes); //Log.i("iv bytes", bytearrToString(ivbytes)); outcipher = new CipherOutputStream(out, datac); outzip = new ZipOutputStream(outcipher); outzip.setMethod(ZipOutputStream.DEFLATED); //write the first file (e-mail address) String androidVersion = android.os.Build.VERSION.RELEASE; String deviceName = android.os.Build.MODEL; ZipEntry infoEntry = new ZipEntry("info.txt"); outzip.putNextEntry(infoEntry); outzip.write((androidVersion + "\n" + deviceName).getBytes()); outzip.closeEntry(); ZipEntry emailEntry = new ZipEntry(emailFilename); outzip.putNextEntry(emailEntry); outzip.write(email.getBytes()); outzip.closeEntry(); ZipEntry csvEntry = new ZipEntry(csvFilename); outzip.putNextEntry(csvEntry); outzip.write(sb.toString().getBytes()); outzip.closeEntry(); } catch (Exception e) { e.printStackTrace(); } finally { try { outzip.close(); outcipher.close(); out.close(); } catch (IOException e) { //ignore } catch (NullPointerException ne) { //ignore } } //here we actually upload the files String containerFilename = basename + "_container.zip"; File containerFile = new File(appDir, containerFilename); zipUp(containerFile, new File[] { file, keyfile }); boolean success = uploadFile(containerFile); containerFile.delete(); file.delete(); keyfile.delete(); if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) { DbAdapter dba2 = new DbAdapter(this); dba2.open(); dba2.clearDB(); dba2.close(); } if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) { Editor e = prefs.edit(); e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails e.commit(); } String s = success ? "Upload complete. Thanks!" : "Upload Failed"; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this) .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s) .setAutoCancel(true).setOngoing(false); if (mManual) { //only show a notification if we manually upload the file. Intent toLaunch = new Intent(UploadFile.this, MainScreen.class); //The notification has to go somewhere. PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(1, mBuilder.build()); } stopSelf(); }