/** * Encrypt a properties if the data definition (model-specific) requires it. * * @param propertyQName the property qualified name * @param inbound the property to encrypt * @return the encrypted property or the original if encryption is not required */ public Serializable encrypt(QName propertyQName, Serializable inbound) { PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName); if (inbound == null || propertyDef == null || !(propertyDef.getDataType().getName().equals(DataTypeDefinition.ENCRYPTED))) { return inbound; } if (inbound instanceof SealedObject) { return inbound; } Serializable outbound = encryptor.sealObject(KeyProvider.ALIAS_METADATA, null, inbound); // Done return outbound; }
/** * Decrypt a property if the data definition (model-specific) requires it. * * @param propertyQName the property qualified name * @param inbound the property to decrypt * @return the decrypted property or the original if it wasn't encrypted */ public Serializable decrypt(QName propertyQName, Serializable inbound) { PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName); if (inbound == null || propertyDef == null || !(propertyDef.getDataType().getName().equals(DataTypeDefinition.ENCRYPTED))) { return inbound; } if (!(inbound instanceof SealedObject)) { return inbound; } try { Serializable outbound = encryptor.unsealObject(KeyProvider.ALIAS_METADATA, inbound); // Done return outbound; } catch(KeyException e) { throw new AlfrescoRuntimeException("Invalid metadata decryption key", e); } }
@Override Serializable convert(Serializable value) { if (value == null) { return null; } else if (value instanceof SealedObject) { return value; } else { throw new IllegalArgumentException("Encrypted properties must be encrypted by the client."); } }
@Override public Serializable sealObject(String keyAlias, AlgorithmParameters params, Serializable input) { if (input == null) { return null; } Cipher cipher = getCipher(keyAlias, params, Cipher.ENCRYPT_MODE); if (cipher == null) { return input; } try { return new SealedObject(input, cipher); } catch (Exception e) { throw new AlfrescoRuntimeException("Failed to seal object", e); } }
/** * Seals the given cleartext key, using the password provided at * construction time */ SealedObject seal(Key key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // seal key Cipher cipher; PBEWithMD5AndTripleDESCipher cipherSpi; cipherSpi = new PBEWithMD5AndTripleDESCipher(); cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(), "PBEWithMD5AndTripleDES"); cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec); return new SealedObjectForKeyProtector(key, cipher); }
/** * Seals the given cleartext key, using the password provided at * construction time */ SealedObject seal(Key key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // seal key Cipher cipher; PBEWithMD5AndTripleDESCipher cipherSpi; cipherSpi = new PBEWithMD5AndTripleDESCipher(); cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(), "PBEWithMD5AndTripleDES"); cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec); return new SealedObjectForKeyProtector(key, cipher); }
public static String encryptAndSerializeObject(final Serializable object, final SecretKey key) { if (object == null) { throw new IllegalArgumentException("object must not be null"); } try { final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); final SealedObject sealedobject = new SealedObject(object, cipher); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(sealedobject); final byte[] bytes = bos.toByteArray(); return BaseEncoding.base64().encode(bytes); } catch (final Exception e) { log.error(e.toString(), e); throw new ElasticsearchException(e.toString()); } }
public static Serializable decryptAnDeserializeObject(final String string, final SecretKey key) { if (string == null) { throw new IllegalArgumentException("string must not be null"); } try { final byte[] userr = BaseEncoding.base64().decode(string); final ByteArrayInputStream bis = new ByteArrayInputStream(userr); final ObjectInputStream in = new ObjectInputStream(bis); final SealedObject ud = (SealedObject) in.readObject(); return (Serializable) ud.getObject(key); } catch (final Exception e) { log.error(e.toString(), e); throw new ElasticsearchException(e.toString()); } }
@Test public void encryptAndDecryptMessage() throws Exception { MessageModel newMessage = new MessageModel(false, "OWNER", 1); PublicKey pubTest = Settings.getInstance().getPublicKey(); PrivateKey privTest = Settings.getInstance().getPrivateKey(); Log.d(LOG_TAG, "plain: " + newMessage.getOwnerName()); SealedObject encrypted = Crypto.encryptBytes(newMessage, pubTest); assertNotNull("Encrypted SealedObject is null", encrypted); Object decrypted = Crypto.decryptBytes(encrypted, privTest); assertNotNull("Decrypted Object is null", decrypted); MessageModel oldMessage = (MessageModel) decrypted; assertEquals("Values before/after encryption don't match", oldMessage.getOwnerName(), "OWNER"); }
public synchronized Object sealObject(Object object) throws CryptoException { try { if (useSealedObject) { return new SealedObject((Serializable)object, encryptCipher); } AccessibleByteArrayOutputStream baos = new AccessibleByteArrayOutputStream(1 << 13); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); oos.flush(); oos.close(); return encrypt(baos.getBuffer(), 0, baos.getCount()); } catch ( Exception e ) { try { initEncryptCipher(); } catch (CryptoException err) { //shouldn't happen } throw new CryptoException(CorePlugin.Event.TEIID10013, CorePlugin.Util.gs(CorePlugin.Event.TEIID10013, e.getMessage())); } }
/** * Gets the security context from the exchange. * @param exchange the exchange * @param create create a new security context if one does not already exist in the exchange or if it is not still valid * @return the security context, or null if create is false and one didn't already exist or was not valid */ public SecurityContext getContext(Exchange exchange, boolean create) { SecurityContext securityContext = null; Property property = exchange.getContext().getProperty(EXCHANGE_PROPERTY, Scope.EXCHANGE); if (property != null) { Object object = property.getValue(); if (object instanceof SecurityContext) { securityContext = (SecurityContext)object; } else if (object instanceof SealedObject) { PrivateCrypto privateCrypto = _systemSecurity.getPrivateCrypto(); if (privateCrypto == null) { throw new IllegalStateException("privateCrypto == null"); } securityContext = (SecurityContext)privateCrypto.unseal((SealedObject)object); } else if (object != null) { throw new IllegalArgumentException(object.getClass().getName() + " != " + EXCHANGE_PROPERTY); } } UUID systemUUID = _systemSecurity.getUUID(); if ((securityContext == null || !securityContext.isValid(systemUUID)) && create) { Long timeoutMillis = _systemSecurity.getSecurityContextTimeoutMillis(); securityContext = new DefaultSecurityContext(systemUUID, timeoutMillis); } return securityContext; }
/** * readObject(ObjectInputStream s) method testing. Tests if the * serialization/deserialization works correctly: object is serialized, * deserialized, the content od deserialized object equals to the content of * initial object. */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "!Serialization", args = {} ) public void testReadObject() throws Exception { String secret = "secret string"; SealedObject so = new SealedObject(secret, new NullCipher()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(so); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( bos.toByteArray())); SealedObject so_des = (SealedObject) ois.readObject(); assertEquals("The secret content of deserialized object " + "should be equal to the secret content of initial object", secret, so_des.getObject(new NullCipher())); assertEquals("The value returned by getAlgorithm() method of " + "deserialized object should be equal to the value returned " + "by getAlgorithm() method of initial object", so .getAlgorithm(), so_des.getAlgorithm()); }
/** * getAlgorithm() method testing. Tests if the returned value equals to the * corresponding value of Cipher object. */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "getAlgorithm", args = {} ) public void testGetAlgorithm() throws Exception { String secret = "secret string"; String algorithm = "DES"; KeyGenerator kg = KeyGenerator.getInstance(algorithm); Key key = kg.generateKey(); Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key); SealedObject so = new SealedObject(secret, cipher); assertEquals("The algorithm name should be the same as used " + "in cipher.", algorithm, so.getAlgorithm()); }
/** * Seals the given cleartext key, using the password provided at * construction time */ SealedObject seal(Key key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.RANDOM.nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // seal key Cipher cipher; PBEWithMD5AndTripleDESCipher cipherSpi; cipherSpi = new PBEWithMD5AndTripleDESCipher(); cipher = new CipherForKeyProtector(cipherSpi, PROV, "PBEWithMD5AndTripleDES"); cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec); return new SealedObjectForKeyProtector(key, cipher); }
/** Encrypts the Serializable object with AES * @param plaintext the Serializable object to encrypt * @param password the password to use for encryption, if it's null or empty the default pass will be used instead * @return an encrypter String formatted as json containing the used cipher and the encrypted object */ public static String encryptAES(Serializable plaintext, String password) { try{ final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); final PBEKeySpec pbeKeySpec = new PBEKeySpec( (password==null || password.equalsIgnoreCase(""))?defaultPass:password.toCharArray() ); final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(AES_ALG); final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec); final Cipher cipher = Cipher.getInstance(AES_ALG); cipher.init(Cipher.ENCRYPT_MODE,secretKey,pbeParamSpec); return gson.toJson(new SealedObject(plaintext,cipher)); } catch(Exception e) { e.printStackTrace(); } return null; }
/** Decrypts an AES encrypted String * @param encString the String to decrypt, formatted as json containing the used cipher and the encrypted object * @param password the password to use for decryption, if it's null or empty the default pass will be used instead * @return a Serializable decrypted object */ public static Serializable decryptAES(String encString, String password) { try{ final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); final PBEKeySpec pbeKeySpec = new PBEKeySpec( (password==null || password.equalsIgnoreCase(""))?defaultPass:password.toCharArray() ); final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(AES_ALG); final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec); final Cipher cipher = Cipher.getInstance(AES_ALG); cipher.init(Cipher.DECRYPT_MODE,secretKey,pbeParamSpec); return (Serializable) (gson.fromJson(encString, SealedObject.class)).getObject(cipher); } catch(Exception e) { e.printStackTrace(); } return null; }
public Collection<Ftp> readFtpHistory(Cipher cipher, String intallationPath) { String path = intallationPath + "/" + FTP_FOLDER; File directory = new File(path); File[] subfiles = directory.listFiles(); Collection<Ftp> ftps = new ArrayList<Ftp>(); for (int i = 0; i < subfiles.length; i++) { try { String ftpPath = subfiles[i].getAbsolutePath(); ObjectInputStream fRo = new ObjectInputStream( new GZIPInputStream(new FileInputStream(ftpPath))); SealedObject sealedObject = (SealedObject) fRo.readObject(); Ftp ftp = (Ftp) sealedObject.getObject(cipher); ftps.add(ftp); fRo.close(); } catch (Exception e) { // throw new LoadingException("Can't load ftp! " + // e.getMessage()); e.printStackTrace(); } } return ftps; }
/** * Unseals the sealed key. */ Key unseal(SealedObject so) throws NoSuchAlgorithmException, UnrecoverableKeyException { try { // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey skey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); SealedObjectForKeyProtector soForKeyProtector = null; if (!(so instanceof SealedObjectForKeyProtector)) { soForKeyProtector = new SealedObjectForKeyProtector(so); } else { soForKeyProtector = (SealedObjectForKeyProtector)so; } AlgorithmParameters params = soForKeyProtector.getParameters(); if (params == null) { throw new UnrecoverableKeyException("Cannot get " + "algorithm parameters"); } PBEWithMD5AndTripleDESCipher cipherSpi; cipherSpi = new PBEWithMD5AndTripleDESCipher(); Cipher cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(), "PBEWithMD5AndTripleDES"); cipher.init(Cipher.DECRYPT_MODE, skey, params); return (Key)soForKeyProtector.getObject(cipher); } catch (NoSuchAlgorithmException ex) { // Note: this catch needed to be here because of the // later catch of GeneralSecurityException throw ex; } catch (IOException ioe) { throw new UnrecoverableKeyException(ioe.getMessage()); } catch (ClassNotFoundException cnfe) { throw new UnrecoverableKeyException(cnfe.getMessage()); } catch (GeneralSecurityException gse) { throw new UnrecoverableKeyException(gse.getMessage()); } }
public static void main(String[] args) throws IOException, IllegalBlockSizeException, ClassNotFoundException, BadPaddingException { Cipher nullCipher = new NullCipher(); // Seal SealedObject so = new SealedObject(SEAL_STR, nullCipher); // Unseal and compare if (!(SEAL_STR.equals(so.getObject(nullCipher)))) { throw new RuntimeException("Unseal and compare failed."); } System.out.println("Test passed."); }
@Override protected List<EncryptedBallotAndWrappedKey> call() throws Exception { // Need to create the stream here, so it'll be available to the executor thread try (InputStream encBallotsInputStream = Files.newInputStream(encryptedBallotsFile.toPath(), StandardOpenOption.READ)) { return (List<EncryptedBallotAndWrappedKey>) SafeObjectReader.safeReadObject( ArrayList.class, Arrays.asList(EncryptedBallotAndWrappedKey.class, SealedObject.class), maxObjects, maxBytes, encBallotsInputStream); } }
/** * Wraps any serializable object into a SealedObject and returns the corresponding byte array * * @param object the object to seal * @return the byte array representing the SealedObject (locked with the cipher and key provided to the constructor) * @throws CryptoOperationRuntimeException * @see #unsealObject(byte[], long) the matching unwrapping method */ public byte[] sealObject(Serializable object) { ByteArrayOutputStream byteArrayOutputStream = null; try { cipher.init(Cipher.ENCRYPT_MODE, key, SecureRandomFactory.createPRNG()); SealedObject sealedObject = new SealedObject(object, cipher); byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(sealedObject); } catch (InvalidKeyException | IOException | IllegalBlockSizeException e) { throw new CryptoOperationRuntimeException("cannot seal object", e); } return byteArrayOutputStream.toByteArray(); }
/** * Parses a SealedObject from the given byte array and retrieves the original wrapped object * * @param encryptedObject a byte array representing a SealedObject * @param maxBytes the maximum size allowed for the read object * @return the original Serializable object * @throws CryptoOperationRuntimeException * @see #sealObject(java.io.Serializable) the matching wrapping operation */ public Object unsealObject(byte[] encryptedObject, long maxBytes) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedObject); SealedObject sealedObject = SafeObjectReader.safeReadObject(SealedObject.class, new ArrayList<>(), MAX_OBJECTS, maxBytes, byteArrayInputStream); return sealedObject.getObject(key); } catch (IOException | ClassNotFoundException | InvalidKeyException | NoSuchAlgorithmException e) { throw new CryptoOperationRuntimeException("cannot unseal object", e); } }