/** * Encrypt the secret with RSA. * * @param secret the secret. * @return the encrypted secret. * @throws Exception */ public String encrypt(String secret) throws Exception { KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); keyStore.load(null); KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Cipher inputCipher = Cipher.getInstance(RSA_ALGORITHM); inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher); cipherOutputStream.write(secret.getBytes()); cipherOutputStream.close(); return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT); }
@Nullable static String encryptMessage(@NonNull String plainMessage) throws SecureStorageException { try { Cipher input; if (Build.VERSION.SDK_INT >= M) { input = Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_MARSHMALLOW_PROVIDER); } else { input = Cipher.getInstance(KEY_TRANSFORMATION_ALGORITHM, KEY_CIPHER_JELLYBEAN_PROVIDER); } input.init(Cipher.ENCRYPT_MODE, getPublicKey()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream( outputStream, input); cipherOutputStream.write(plainMessage.getBytes(KEY_CHARSET)); cipherOutputStream.close(); byte[] values = outputStream.toByteArray(); return Base64.encodeToString(values, Base64.DEFAULT); } catch (Exception e) { throw new SecureStorageException(e.getMessage(), e, KEYSTORE_EXCEPTION); } }
private void EncryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EncryptActionPerformed try{ FileInputStream file = new FileInputStream(file_path.getText()); FileOutputStream outStream = new FileOutputStream("Encrypt.jpg"); byte k[]="CooL2116NiTh5252".getBytes(); SecretKeySpec key = new SecretKeySpec(k, "AES"); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.ENCRYPT_MODE, key); CipherOutputStream cos = new CipherOutputStream(outStream, enc); byte[] buf = new byte[1024]; int read; while((read=file.read(buf))!=-1){ cos.write(buf,0,read); } file.close(); outStream.flush(); cos.close(); JOptionPane.showMessageDialog(null, "The file encrypted Successfully"); }catch(Exception e){ JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }
private void DecryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DecryptActionPerformed try{ FileInputStream file = new FileInputStream("C:\\Users\\SMP\\Documents\\NetBeansProjects\\Rohan\\Encrypt.jpg"); FileOutputStream outStream = new FileOutputStream("Decrypt.jpg"); byte k[]="CooL2116NiTh5252".getBytes(); SecretKeySpec key = new SecretKeySpec(k, "AES"); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.DECRYPT_MODE, key); CipherOutputStream cos = new CipherOutputStream(outStream, enc); byte[] buf = new byte[1024]; int read; while((read=file.read(buf))!=-1){ cos.write(buf,0,read); } file.close(); outStream.flush(); cos.close(); JOptionPane.showMessageDialog(null, "The image was decrypted successfully"); Runtime.getRuntime().exec("rundll32 url.dll, FileProtocolHandler "+"Decrypt.jpg"); }catch(Exception e){ JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }
/** * The CICO PBE RW test specific part of the super.doTest(). Implements the * scenario in accordance to the class description. * @param type byteArrayBuffering or intByteBuffering * @throws IOException any I/O operation failed. * @throws GeneralSecurityException any security error. */ @Override public void proceedTest(String type) throws IOException, GeneralSecurityException { ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput, getDecryptCipher())) { if (type.equals(CICO_PBE_Test.BYTE_ARR_BUFFER)) { proceedTestUsingByteArrayBuffer(ciOutput); } else { proceedTestUsingIntBuffer(ciOutput); } ciOutput.flush(); } // Compare input and output if (!TestUtilities.equalsBlock(plainText, baOutput.toByteArray(), TEXT_SIZE)) { throw new RuntimeException("outputText not same with expectedText" + " when test " + type); } }
private void decryptWithEmptyAAD() throws Exception { System.out.println("decryptWithEmptyAAD() started"); // initialize it with empty AAD to get exception during decryption Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE, encryptCipher.getParameters()); try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decryptCipher)) { if (decrypt(ciOutput, baOutput)) { throw new RuntimeException( "Decryption has been perfomed successfully in" + " spite of the decrypt Cipher has NOT been" + " initialized with AAD"); } } System.out.println("decryptWithEmptyAAD() passed"); }
private void decryptWithWrongAAD() throws Exception { System.out.println("decrypt with wrong AAD"); // initialize it with wrong AAD to get an exception during decryption Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE, encryptCipher.getParameters()); byte[] someAAD = Helper.generateBytes(AAD_SIZE + 1); decryptCipher.updateAAD(someAAD); // init output stream try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decryptCipher);) { if (decrypt(ciOutput, baOutput)) { throw new RuntimeException( "A decryption has been perfomed successfully in" + " spite of the decrypt Cipher has been" + " initialized with fake AAD"); } } System.out.println("Passed"); }
@Override public void runTest(BufferType bufType) throws IOException, GeneralSecurityException { ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); try (CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decryptCipher)) { if (bufType == BufferType.BYTE_ARRAY_BUFFERING) { doByteTest(ciOutput); } else { doIntTest(ciOutput); } } check(plaintext, baOutput.toByteArray()); }
public static byte[] streamEncrypt(String message, SecretKey key, MessageDigest digest) throws Exception { byte[] data; Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); encCipher.init(Cipher.ENCRYPT_MODE, key); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DigestOutputStream dos = new DigestOutputStream(bos, digest); CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) { try (ObjectOutputStream oos = new ObjectOutputStream(cos)) { oos.writeObject(message); } data = bos.toByteArray(); } if (debug) { System.out.println(DatatypeConverter.printHexBinary(data)); } return data; }
public void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Exception { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); SecretKey desKey = skf.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for // SunJCE if (mode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, desKey); CipherInputStream cis = new CipherInputStream(is, cipher); doCopy(cis, os); } else if (mode == Cipher.DECRYPT_MODE) { cipher.init(Cipher.DECRYPT_MODE, desKey); CipherOutputStream cos = new CipherOutputStream(os, cipher); doCopy(is, cos); } }
/** * <p>Wraps an <code>OutputStream</code> with a <code>CipherOutputStream</code> using this encryptor's cipher.</p> * <p>If an <code>ivLength</code> has been specified or an explicit IV has been set during construction * and <code>prependIV</code> is set to <code>true</code> this method will write an IV to the <code>OutputStream</code> before wrapping it.</p> * @param os * @return * @throws GeneralSecurityException * @throws IOException */ public CipherOutputStream wrapOutputStream(OutputStream os) throws GeneralSecurityException, IOException { Cipher cipher = getCipher(); if(!generateIV) { iv = null; } else if(iv == null && ivLength > 0) { generateIV(); } if(iv != null) { cipher.init(Cipher.DECRYPT_MODE, getKey(), getAlgorithmParameterSpec(iv)); } else { cipher.init(Cipher.DECRYPT_MODE, getKey()); iv = cipher.getIV(); } if(prependIV && iv != null) { os.write(iv); } return new CipherOutputStream(os, cipher); }
public String encryptString(String initialText) { try { KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey(); Cipher inCipher = Cipher.getInstance(CIPHER_TRANSFORMATION, CIPHER_PROVIDER); inCipher.init(Cipher.ENCRYPT_MODE, publicKey); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inCipher); cipherOutputStream.write(initialText.getBytes("UTF-8")); cipherOutputStream.close(); byte[] vals = outputStream.toByteArray(); String cipher = Base64.encodeToString(vals, Base64.DEFAULT); save(cipher); return cipher; } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } return null; }
public boolean decrypt(String file, String dest,Key key) { try{ Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024]; int r; while ((r = is.read(buffer)) >= 0) { System.out.println(); cos.write(buffer, 0, r); } cos.close(); out.close(); is.close(); return true; }catch (Exception e){ e.printStackTrace(); return false; } }
@SuppressWarnings("InsecureCryptoUsage") public void testCorruptDecryptEmpty(Iterable<TestVector> tests) throws Exception { for (TestVector t : tests) { Cipher cipher = Cipher.getInstance(t.algorithm); cipher.init(Cipher.DECRYPT_MODE, t.key, t.params); cipher.updateAAD(t.aad); byte[] ct = Arrays.copyOf(t.ct, t.ct.length); ct[ct.length - 1] ^= (byte) 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); CipherOutputStream cos = new CipherOutputStream(os, cipher); cos.write(ct); try { // cos.close() should call cipher.doFinal(). cos.close(); byte[] decrypted = os.toByteArray(); fail( "this should fail; decrypted:" + TestUtil.bytesToHex(decrypted) + " pt: " + TestUtil.bytesToHex(t.pt)); } catch (IOException ex) { // expected } } }
@Test public void testInputStream() throws Exception { AES aes = new AES(); String orig = "I'm a password, really"; ByteArrayInputStream bais = new ByteArrayInputStream(orig.getBytes()); CipherInputStream cis = aes.inputStream(bais, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Symm.base64.encode(cis, baos); cis.close(); byte[] b64encrypted; System.out.println(new String(b64encrypted=baos.toByteArray())); baos.reset(); CipherOutputStream cos = aes.outputStream(baos, false); Symm.base64.decode(new ByteArrayInputStream(b64encrypted),cos); cos.close(); Assert.assertEquals(orig, new String(baos.toByteArray())); }
public void write (Kryo kryo, Output output, Object object) { Cipher cipher = getCipher(Cipher.ENCRYPT_MODE); CipherOutputStream cipherStream = new CipherOutputStream(output, cipher); Output cipherOutput = new Output(cipherStream, 256) { public void close () throws KryoException { // Don't allow the CipherOutputStream to close the output. } }; serializer.write(kryo, cipherOutput, object); cipherOutput.flush(); try { cipherStream.close(); } catch (IOException ex) { throw new KryoException(ex); } }
public void write (Kryo kryo, Output output, Object object) { Cipher cipher = getCipher(Cipher.ENCRYPT_MODE); CipherOutputStream cipherStream = new CipherOutputStream(output, cipher); Output cipherOutput = new Output(cipherStream, 256) { public void close () throws KryoException { // Don't allow the CipherOutputStream to close the output. } }; kryo.writeObject(cipherOutput, object, serializer); cipherOutput.flush(); try { cipherStream.close(); } catch (IOException ex) { throw new KryoException(ex); } }
private byte[] encryptString(Key key, String service, String value) throws CryptoFailedException { try { Cipher cipher = Cipher.getInstance(ENCRYPTION_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, key); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // write initialization vector to the beginning of the stream byte[] iv = cipher.getIV(); outputStream.write(iv, 0, iv.length); // encrypt the value using a CipherOutputStream CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher); cipherOutputStream.write(value.getBytes("UTF-8")); cipherOutputStream.close(); return outputStream.toByteArray(); } catch (Exception e) { throw new CryptoFailedException("Could not encrypt value for service " + service, e); } }
public WriteEncryptedFile(String filename, Key publicKey){ try{ //Step 1: generate random symmetric key (AES algorithm): KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey aesKey = kgen.generateKey(); //Step 2: Create encoding cipher using public key (RSA algorithm): Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey); //Step 3: Open file stream: FileOutputStream file = new FileOutputStream(filename); //Step 4: Encode symmetric key using encoding cipher, and write to file: file.write(rsaCipher.doFinal(aesKey.getEncoded())); //Step 5: Open encrypted stream using symmetric key (AES algorithm): Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); CipherOutputStream out = new CipherOutputStream(file, cipher); bufferedWrite = new BufferedWriter(new OutputStreamWriter(out)); } catch (Exception e){ e.printStackTrace(); } }