This is an automated email from the ASF dual-hosted git repository.
rombert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-whiteboard.git
The following commit(s) were added to refs/heads/master by this push:
new 622ff8c SLING-7255 - Donating Sling Resource Encryption Utils
622ff8c is described below
commit 622ff8c23334dc0b49cd4ecdb5f2ab02409592cb
Author: JE Bailey <[email protected]>
AuthorDate: Fri Jan 12 16:39:19 2018 +0200
SLING-7255 - Donating Sling Resource Encryption Utils
Initial contribution.
---
encrypt/.gitignore | 5 +
encrypt/LICENSE | 201 +++++++++++++
encrypt/README.md | 107 +++++++
encrypt/pom.xml | 89 ++++++
.../resource/encryption/EncryptableValueMap.java | 43 +++
.../resource/encryption/EncryptionException.java | 39 +++
.../resource/encryption/EncryptionProvider.java | 80 +++++
.../sling/resource/encryption/KeyProvider.java | 67 +++++
.../encryption/impl/AesGcmEncryptionProvider.java | 186 ++++++++++++
.../encryption/impl/EncryptPostProcessor.java | 102 +++++++
.../impl/EncryptableValueMapAdapterFactory.java | 47 +++
.../resource/encryption/impl/JCEKSKeyProvider.java | 133 ++++++++
.../resource/encryption/impl/OSGiKeyProvider.java | 130 ++++++++
.../sling/resource/encryption/package-info.java | 15 +
.../wrapper/EncryptableValueMapDecorator.java | 180 +++++++++++
encrypt/src/main/javacc/locator.jj | 333 +++++++++++++++++++++
.../encryption/Base64EncryptionProvider.java | 56 ++++
.../resource/encryption/BaseEncryptionTest.java | 202 +++++++++++++
.../apache/sling/resource/encryption/Create.java | 54 ++++
.../encryption/EncryptionKeyStoreTest.java | 133 ++++++++
.../encryption/EncryptionOSGiStoreTest.java | 134 +++++++++
encrypt/src/test/resources/data.json | 17 ++
encrypt/src/test/resources/data2.json | 17 ++
encrypt/src/test/resources/data3.json | 17 ++
encrypt/src/test/resources/keystore.jks | Bin 0 -> 960 bytes
25 files changed, 2387 insertions(+)
diff --git a/encrypt/.gitignore b/encrypt/.gitignore
new file mode 100644
index 0000000..21b01f2
--- /dev/null
+++ b/encrypt/.gitignore
@@ -0,0 +1,5 @@
+*.class
+.settings
+.classpath
+
+/target/
diff --git a/encrypt/LICENSE b/encrypt/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/encrypt/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/encrypt/README.md b/encrypt/README.md
new file mode 100644
index 0000000..8b14c6c
--- /dev/null
+++ b/encrypt/README.md
@@ -0,0 +1,107 @@
+# Resource Encryption API
+API's to facillitate the encryption of Sling resource values
+
+# When to use this
+Due to policies, you may encounter use cases where stored data should be
encrypted so that read access to the JCR does not mean that you have access to
the encrypted data.
+
+Examples of policies:
+1. Requirement to secure sensitive data at rest
+2. Prevent operational and/or support from being able to view sensitive data
stored in the JCR
+
+The Resource Encryption utils provide a framework for data to be encrypted
programatically or handled automatically as part of a data submission via a
POST.
+
+# How to use this
+* Configure a KeyProvider
+* Configure an EncryptionProvider to target the Configured KeyProvider
+
+Once the EncryptionProvider is configured, the EncryptPostProcessor and the
EncryptableValueMapAdatperFactory will be enabled
+
+# Overview of the API's
+## EncryptableValueMap
+Wraps the encryption and decryption process of resource values so that a
common framework can be put in place to handle encryption needs.
+
+## EncryptionProvider
+Manages the encryption and decryption process specifically so that an entity
can provide an encryption algorithm that fits the need of their organization.
+
+## KeyProvider
+Manages the retreival of Secret Keys so that they keys used to encrypt and
decrypt data can be done in a robust way and with the ability to handle key
rotations if needed.
+
+
+# Performing Encrytpion
+
+## Encrypting Data via POST
+This bundle supplies a SingPostProcessor service that looks for for form
fields to submit. This is a configurable service that can support two different
method of identification
+
+### Method 1 - @Encrypt secondary field
+In the same manner of controlling content as the servlets.post bundle you are
able to add an additional hidden field to a form that will let the Post servlet
encrypt the value submitted in the non hidden field.
+
+Example:
+```html
+ <input type="text" name="personalid"/>
+ <input type="hidden" name="personalid@Encrypt" value="ignored" />
+```
+
+In the example the @Encrypt suffix in the field name lets the processor know
that the value identified by the String to the left of the ampersand needs to
be encrypted.
+
+### Method 2 - @Encrypt inline
+To make it as easy as possible to identify fields that need to be encrypted
this Service can be configured in the OSGi to accept fields where the suffix
can be applied directly to the field name that needs to be encrypted.
+```html
+ <input type="text" name="personalid@Encrypt" />
+```
+
+### Configurable Suffix identifier
+To avoid naming conflict or limitations applied by third party libraries. The
suffix that is used to trigger the encryption is configurable as well via the
OSGi console.
+
+## Encrypting Data via code
+To encrypt a property in a resource. The resource needs to be adapated to an
EncryptionValueMap. Then use the encrypt method to secure the property
leveraging the ModifiableValueMap class
+```java
+EncryptionValueMap map = resource.adaptTo(EncryptionValueMap.class);
+map.encrypt("ssn");
+
+resourceResolver.commit()
+```
+An exception will be thrown if attempting to modify a resource that you don't
have permission to or if the resource was provided by a ResourceProvider that
is not Modifiable.
+
+When encrypt is called on a value that is already encrypted, if the encryption
provider supports the decoding of the existing value, that value will be
re-encrypted.
+
+
+## Accessing Encrypted Values
+Once a resource has an encrypted value. Access to decrypt that value is built
into the normal ValueMap accessors
+ ```java
+EncryptionValueMap map = resource.adaptTo(EncryptionValueMap.class);
+String plaintext = map.get("ssn");
+```
+
+# Encryption Providers
+
+## AesGcmEncryptionProvider
+
+Encrypts a String and returns the result in a Base64 format
+
+A standard encrypted String form this implementation takes the format of
+
+ 🔒2u7G5DT0uPXQ1606a+NERe9EVtuH6PR31MO7FjN4NZw+KKc=
+
+This String consists of a configurable prefix to identify that the String is
encrypted followed by a byte[] that has been Base64 encoded.
+
+The decoded byte array consists of the following three segments
+* IV - represents the initailization vector
+* Key ID - is a unique identifier for the KeyProvider to identify the
associated secret
+* Encrypted data - with the remainder representing the encrypted data
+
+Additionally the GCM encryption process takes the property name as additional
authentication data. So that an encrypted value is only decryptable when it is
associated with the original property name.
+
+# Key Providers
+KeyProviders are used to provision keys to the EncryptionProvider to allow for
the keys to be managed independently
+
+## JCESKeyProvider
+Utilizing the java keystore mechanism, the JCESKeyProvider requires a Java
KeyStore to be created and maintained separatly from the OSGi environment. The
JCESKeyProvider is used to identify the alias that is the primary key for
encryption, as well as supporting secondary aliases to be used for decryption
purposes.
+
+The use of secondary aliases is to support **key rotation**. Since the
encrypted string self identified the id of the alias to use, when there is a
need to change the key. A new primary alias is identified and the old primary
is moved to the secondary aliases.This allows for processes to continue to
decrypt Strings that are stored with the old alias while simultaneously
encrytping data with the new alias.
+To facilitate a proper secure rotation there would still be a need to manually
process the old keys and reencrypt them with the new alias.
+
+Re-encryption can be handled by the EncrytableValueMap as the encrypt() method
will re-encrypt a value that has a supported decryption alias id.
+
+## OSGiKeyProvider
+Stores a list of Base64 encoded keys that are entered via the OSGi admin
console. This is useful for testing of the Encryption Process as well as for
environments where access to the underlying filesystem is limited or
restricted, however serious consideration needs to be considered before relying
on this method for long term storage of sensitive information.
+
diff --git a/encrypt/pom.xml b/encrypt/pom.xml
new file mode 100644
index 0000000..cb7002c
--- /dev/null
+++ b/encrypt/pom.xml
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!-- Copyright 2016 JE Bailey Licensed under the Apache License, Version
+ 2.0 (the "License"); you may not use this file except in compliance
with
+ the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
+ Unless required by applicable law or agreed to in writing, software
distributed
+ under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES
+ OR CONDITIONS OF ANY KIND, either express or implied. See the License
for
+ the specific language governing permissions and limitations under the
License. -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>sling</artifactId>
+ <version>29</version>
+ </parent>
+
+ <artifactId>org.apache.sling.resource.encryption</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <packaging>bundle</packaging>
+
+ <name>Encryption Tools for Apache Sling</name>
+
+ <properties>
+ <sling.java.version>8</sling.java.version>
+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>maven-sling-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.api</artifactId>
+ <version>2.9.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.4</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+
<artifactId>org.apache.sling.testing.sling-mock</artifactId>
+ <version>2.2.14</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+
<artifactId>org.apache.sling.testing.osgi-mock</artifactId>
+ <version>2.3.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-jcr-commons</artifactId>
+ <version>2.15.5</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.findbugs</groupId>
+ <artifactId>jsr305</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.servlets.post</artifactId>
+ <version>2.3.22</version>
+ <type>bundle</type>
+ </dependency>
+ </dependencies>
+ <description>Encryption utilities</description>
+</project>
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptableValueMap.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptableValueMap.java
new file mode 100644
index 0000000..2d2fdce
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptableValueMap.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import org.apache.sling.api.resource.ModifiableValueMap;
+
+/**
+ * The <code>EncryptableValueMap</code> provides for specifying the encryption
+ * and decryption specific values within a resource.
+ *
+ */
+public interface EncryptableValueMap extends ModifiableValueMap {
+
+ /**
+ * Encrypts and stores the existing property value. Currently supports
String
+ * and String[]. Values that already encrypted will be re-encrypted.
+ *
+ * @param name
+ * property
+ */
+ void encrypt(String property);
+
+ /**
+ * Decrypts and stores the existing property value . Properties that
are not
+ * encrypted will not change.
+ *
+ * @param name
+ * property
+ */
+ void decrypt(String property);
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionException.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionException.java
new file mode 100644
index 0000000..fdece3b
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionException.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+@SuppressWarnings("serial")
+public class EncryptionException extends Exception {
+
+ public EncryptionException() {
+ super();
+ }
+
+ public EncryptionException(String message, Throwable cause, boolean
enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+
+ public EncryptionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public EncryptionException(String message) {
+ super(message);
+ }
+
+ public EncryptionException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionProvider.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionProvider.java
new file mode 100644
index 0000000..31c5cc3
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/EncryptionProvider.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+/**
+ * Encapsulates the encryption and decryption of data. Implementations of this
+ * interface should guarantee encryption and decryption of types.
+ *
+ * I.e. If you encrypt a byte array this a method then the complimentary
decrypt
+ * will successfully decrypt it. However if you encrypt a String and then
+ * convert that String to bytes it is up to the implementation as to whether
the
+ * decryption of bytes will work.
+ *
+ */
+public interface EncryptionProvider {
+
+ /**
+ * Encrypts a byte array
+ *
+ * @param toEncode
+ * @param aad
+ * optional additional authentication data
+ * @return encrypted byte array
+ * @throws EncryptionException
+ */
+ byte[] encrypt(byte[] toEncode, byte[] aad) throws EncryptionException;
+
+ /**
+ * Decrypts a previously encrypted byte array
+ *
+ * @param toDecode
+ * @param aad
+ * optional additional authentication data
+ * @return
+ * @throws EncryptionException
+ */
+ byte[] decrypt(byte[] toDecode, byte[] aad) throws EncryptionException;
+
+ /**
+ * Encrypts a String and returns a String representation of that
encoding
+ *
+ * @param toEncode
+ * @param aad
+ * optional additional authentication data
+ * @return
+ * @throws EncryptionException
+ */
+ String encrypt(String toEncode, String aad) throws EncryptionException;
+
+ /**
+ * Takes a previously encrypted String and returns the original value
+ *
+ * @param toDecode
+ * @param aad
+ * optional additional authentication data
+ * @return
+ * @throws EncryptionException
+ */
+ String decrypt(String toDecode, String aad) throws EncryptionException;
+
+ /**
+ * Validate whether the String appears to be encrypted
+ *
+ * @param property
+ * @return
+ */
+ boolean isEncrypted(String property);
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/KeyProvider.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/KeyProvider.java
new file mode 100644
index 0000000..c53e7ae
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/KeyProvider.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import java.security.GeneralSecurityException;
+import java.security.Key;
+
+/**
+ * Provides access to a primary key for encryption as well as supporting
+ * multiple secondary keys. Key rotation is enabled by providing a new primary
+ * key and taking the existing primary key and making it a secondary. The
+ * secondary key should be provided until such a time that these key(s) are no
+ * longer needed and/or that all prior uses of that key has been re-encrypted
+ * with the new primary key.
+ *
+ * Each KeyProvider is responsible for maininting an associated list of ID's
for
+ * the contained keys. ID's should be unique for each key and consist of a
+ * byte[] of a consistent length
+ *
+ * Examples implementations of a KeyProvider would provide access:
+ * <ul>
+ * <li>java keystore
+ * <li>osgi based configuration
+ * <li>third party key vaults
+ * </ul>
+ *
+ */
+public interface KeyProvider {
+
+ public static String TYPE = "provider.type";
+
+ /**
+ * Provides an ID to access the primary encryption key, this ID must be
uniquely
+ * associated to the key such that no other key that is managed has the
same ID
+ *
+ * @return an array of byte[] of consistent length that
+ */
+ byte[] getPrimaryKeyID();
+
+ /**
+ * ID's are byte arrays of consistent length which uniquely identifies
a key
+ *
+ * @return length of byte[] for ID
+ */
+ int getIdLength();
+
+ /**
+ * Provides the key associated with this ID, either the primary key or
one of
+ * the maintained secondary keys
+ *
+ * @param alias
+ * @return the requested key, or null if the id does not match an
existing key
+ */
+ Key getKey(byte[] id) throws GeneralSecurityException;
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/AesGcmEncryptionProvider.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/AesGcmEncryptionProvider.java
new file mode 100644
index 0000000..a2d76e6
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/AesGcmEncryptionProvider.java
@@ -0,0 +1,186 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.impl;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.SecureRandom;
+import java.util.Base64;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.GCMParameterSpec;
+
+import org.apache.sling.resource.encryption.EncryptionException;
+import org.apache.sling.resource.encryption.EncryptionProvider;
+import org.apache.sling.resource.encryption.KeyProvider;
+import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.ConfigurationPolicy;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This is a basic implementation of the EncryptionProvider which utilizes
+ * 'AES/GCM/NoPadding' encryption. Before using this in a production
environment
+ * please consult with your Security team. Individual organizations may require
+ * a higer degree of encryption.
+ *
+ */
+@Component(immediate = true, property = { Constants.SERVICE_DESCRIPTION +
"=Sling Encryption Service Provider",
+ Constants.SERVICE_VENDOR
+ + "=The Apache Software Foundation" },
configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Designate(ocd = AesGcmEncryptionProvider.Configuration.class)
+public class AesGcmEncryptionProvider implements EncryptionProvider {
+
+ @ObjectClassDefinition(name = "Apache Sling Encryption Provider -
AES/GCM ")
+ public @interface Configuration {
+
+ @AttributeDefinition(name = "Key Provider Target", description
= "KeyProvider Filter")
+ String keyProvider_target() default "(provider.type=KeyStore)";
+
+ @AttributeDefinition(name = "Encryption Prefix", description =
"Prepends to Encrypted string to identify content that is encrypted")
+ String encryptionPrefix() default "\uD83D\uDD12";
+
+ }
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY, target =
"(name=)")
+ public KeyProvider keyProvider;
+
+ private SecureRandom random;
+
+ private int ivSize;
+
+ private static String ALGORITHM = "AES/GCM/NoPadding";
+
+ private String id = "\uD83D\uDD12";
+
+ private static final Charset UTF8 = Charset.forName("UTF-8");
+
+ private static final int GCM_TAG_LENGTH = 128;
+
+ /** Default logger. */
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ /**
+ * Provides an initial check to make sure that the pieces of the
security
+ * implementation are present
+ *
+ * @param config
+ * @throws GeneralSecurityException
+ */
+ @Activate
+ @Modified
+ public void init(Configuration config) throws GeneralSecurityException {
+ Key secretKey =
keyProvider.getKey(keyProvider.getPrimaryKeyID());
+ Cipher cipher = Cipher.getInstance(ALGORITHM);
+ cipher.init(Cipher.ENCRYPT_MODE, secretKey);
+ this.random = SecureRandom.getInstance("SHA1PRNG");
+ this.ivSize = cipher.getIV().length;
+ this.id = config.encryptionPrefix();
+ }
+
+ private Cipher getCipher(int cipherMode, byte[] iv, byte[] aad, byte[]
keyId) throws GeneralSecurityException {
+ Key secretKey = keyProvider.getKey(keyId);
+ GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH,
iv);
+ Cipher cipher = Cipher.getInstance(ALGORITHM);
+ cipher.init(cipherMode, secretKey, spec);
+ cipher.updateAAD(aad);
+ return cipher;
+ }
+
+ private byte[] generateIV() {
+ byte[] iv = new byte[ivSize];
+ random.nextBytes(iv);
+ return iv;
+ }
+
+ /**
+ * Encrypts the byte[] using a random IV which is then prepended to the
results.
+ */
+ @Override
+ public byte[] encrypt(byte[] toEncode, byte[] aad) throws
EncryptionException {
+ byte[] iv = generateIV();
+ byte[] keyId = keyProvider.getPrimaryKeyID();
+ byte[] byteEncyrpted;
+ try {
+ byteEncyrpted = getCipher(Cipher.ENCRYPT_MODE, iv, aad,
keyId).doFinal(toEncode);
+ } catch (Exception e) {
+ logger.debug("unable to decrypt {}", e);
+ throw new EncryptionException(e);
+ }
+ ByteBuffer buffer = ByteBuffer.allocate(iv.length +
keyId.length + byteEncyrpted.length);
+ buffer.put(iv).put(keyId).put(byteEncyrpted);
+ return buffer.array();
+ }
+
+ /**
+ * Encryption occurs on the underlying bytes of the String. Before
returning the
+ * encrypted bytes are converted to a Base64 representation and
prepended with
+ * an ID to indicate that the String represents an encoded value.
+ */
+ @Override
+ public String encrypt(String value, String aad) throws
EncryptionException {
+ byte[] encoded = encrypt(value.getBytes(), aad.getBytes(UTF8));
+ return id + new String(Base64.getEncoder().encode(encoded),
UTF8);
+ }
+
+ /**
+ * Decrypts the supplied byte[] using the the IV that was prepending to
the
+ * byte[]
+ */
+ @Override
+ public byte[] decrypt(byte[] toDecode, byte[] aad) throws
EncryptionException {
+ byte[] iv = new byte[ivSize];
+ byte[] keyId = new byte[keyProvider.getIdLength()];
+ byte[] byteEncrypted = new byte[toDecode.length - (ivSize +
keyProvider.getIdLength())];
+ ByteBuffer buffer = ByteBuffer.wrap(toDecode);
+ buffer.get(iv).get(keyId).get(byteEncrypted);
+ try {
+ return getCipher(Cipher.DECRYPT_MODE, iv, aad,
keyId).doFinal(byteEncrypted);
+ } catch (GeneralSecurityException e) {
+ throw new EncryptionException(e);
+ }
+ }
+
+ /**
+ * Decrypts the String after first removing the prepending ID and
decrypting the
+ * remaining Base64 encoded byte[]
+ */
+ @Override
+ public String decrypt(String value, String aad) throws
EncryptionException {
+ byte[] bValue = value.substring(id.length()).getBytes(UTF8);
+ byte[] toDecode;
+ try {
+ toDecode = Base64.getDecoder().decode(bValue);
+ } catch (IllegalArgumentException e) {
+ throw new EncryptionException("non-encrypted value");
+ }
+ return new String(decrypt(toDecode, aad.getBytes(UTF8)), UTF8);
+ }
+
+ @Override
+ public boolean isEncrypted(String value) {
+ return (value.startsWith(id) && value.length() > id.length() +
ivSize);
+ }
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptPostProcessor.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptPostProcessor.java
new file mode 100644
index 0000000..1410eb9
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptPostProcessor.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.impl;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.jcr.Session;
+
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.resource.encryption.EncryptionProvider;
+import org.apache.sling.resource.encryption.EncryptableValueMap;
+import org.apache.sling.servlets.post.Modification;
+import org.apache.sling.servlets.post.SlingPostProcessor;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferencePolicyOption;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Component
+@Designate(ocd = EncryptPostProcessor.Configuration.class)
+public class EncryptPostProcessor implements SlingPostProcessor {
+
+ @ObjectClassDefinition(name = "Apache Sling Encryption Post Processor",
description = "Defines options for field encryption")
+ public @interface Configuration {
+
+ @AttributeDefinition(name = "Suffix", description = "Define the
suffix which will uniquely identify a field to be encrypted")
+ String suffix() default "@Encrypt";
+
+ @AttributeDefinition(name = "Inline", description = "Whether
the encrypted flag is set on itself or another field")
+ boolean inline() default false;
+
+ }
+
+ @Reference(policyOption = ReferencePolicyOption.GREEDY)
+ public EncryptionProvider ep;
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ private Configuration config;
+
+ @Override
+ public void process(SlingHttpServletRequest slingRequest,
List<Modification> modifications) throws Exception {
+
+ Set<Modification> mods = modifications.stream()
+ .filter(modification ->
modification.getSource().endsWith(config.suffix())).collect(Collectors.toSet());
+
+ if (mods.size() == 0) {
+ return;
+ }
+
+ ResourceResolver resolver = slingRequest.getResourceResolver();
+ Session session = resolver.adaptTo(Session.class);
+
+ for (Modification mod : mods) {
+ String encryptPropertyPath = mod.getSource();
+
+ String propertyPath = encryptPropertyPath.substring(0,
encryptPropertyPath.lastIndexOf(config.suffix()));
+ String resourcePath = propertyPath.substring(0,
propertyPath.lastIndexOf('/'));
+
+ if (config.inline()) {
+ session.move(encryptPropertyPath, propertyPath);
+ }
+
+ EncryptableValueMap map =
resolver.resolve(resourcePath).adaptTo(EncryptableValueMap.class);
+
map.encrypt(propertyPath.substring(resourcePath.length() + 1,
propertyPath.length()));
+ session.removeItem(encryptPropertyPath);
+ }
+
+ modifications.removeAll(mods);
+
+ mods.forEach(mod -> {
+ logger.debug("removed {} for source {}",
mod.getType().toString(), mod.getSource());
+ });
+ }
+
+ @Activate
+ @Modified
+ public void init(Configuration config) {
+ this.config = config;
+ }
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptableValueMapAdapterFactory.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptableValueMapAdapterFactory.java
new file mode 100644
index 0000000..b084f0a
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/EncryptableValueMapAdapterFactory.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.impl;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.resource.ModifiableValueMap;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.resource.encryption.EncryptionProvider;
+import
org.apache.sling.resource.encryption.wrapper.EncryptableValueMapDecorator;
+import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferencePolicyOption;
+
+@Component(service = { AdapterFactory.class }, property = {
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
+ Constants.SERVICE_DESCRIPTION + "=Default SlingScriptResolver",
+ org.apache.sling.api.adapter.AdapterFactory.ADAPTABLE_CLASSES +
"=org.apache.sling.api.resource.Resource",
+ org.apache.sling.api.adapter.AdapterFactory.ADAPTER_CLASSES
+ +
"=org.apache.sling.resource.encryption.EncryptableValueMap" })
+public class EncryptableValueMapAdapterFactory implements AdapterFactory {
+
+ @Reference(policyOption = ReferencePolicyOption.GREEDY)
+ private EncryptionProvider encryptionProvider;
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <AdapterType> AdapterType getAdapter(Object adaptable,
Class<AdapterType> type) {
+ ValueMap map =
((Resource)adaptable).adaptTo(ModifiableValueMap.class);
+ if (map == null) {
+ map = ((Resource)adaptable).adaptTo(ValueMap.class);
+ }
+ return (AdapterType) new EncryptableValueMapDecorator(map,
encryptionProvider);
+ }
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/JCEKSKeyProvider.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/JCEKSKeyProvider.java
new file mode 100644
index 0000000..99db981
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/JCEKSKeyProvider.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.impl;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.util.HashMap;
+import java.util.zip.CRC32;
+
+import org.apache.sling.resource.encryption.KeyProvider;
+import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.ConfigurationPolicy;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.AttributeType;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+
+@Component(immediate = true, property = { Constants.SERVICE_DESCRIPTION +
"=Sling Java Key Store Provisioner",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
+ KeyProvider.TYPE + "=KeyStore" }, configurationPolicy =
ConfigurationPolicy.REQUIRE)
+@Designate(ocd = JCEKSKeyProvider.Configuration.class)
+public class JCEKSKeyProvider implements KeyProvider {
+
+ @ObjectClassDefinition(name = "Apache Sling Encryption Key Provider -
KeyStore", description = "Apache Sling KeyProvider Implementation - KeyStore")
+ public @interface Configuration {
+
+ @AttributeDefinition(name = "Path", description = "File
Location of Key Store")
+ String path();
+
+ @AttributeDefinition(name = "Password", description = "Password
used to access both the store and alias", type = AttributeType.PASSWORD)
+ String password();
+
+ @AttributeDefinition(name = "Primary", description = "Primary
alias stored in the local KeyStore", type = AttributeType.PASSWORD)
+ String primaryAlias();
+
+ @AttributeDefinition(name = "Secondary", required = false,
description = "Secondary aliases that should be used only for decryption",
cardinality = Integer.MAX_VALUE)
+ String[] secondaryAliases() default {};
+
+ }
+
+ private Configuration config;
+
+ private KeyStore keystore;
+
+ private HashMap<Long, String> aliasIds;
+
+ private Long primaryId;
+
+ @Activate
+ public void init(Configuration config) throws GeneralSecurityException,
IOException {
+ this.config = config;
+ // init keystore
+ keystore = KeyStore.getInstance("JCEKS");
+ InputStream readStream = new FileInputStream(config.path());
+ keystore.load(readStream, config.password().toCharArray());
+ readStream.close();
+
+ aliasIds = new HashMap<>();
+ CRC32 crc = new CRC32();
+ for (String alias : config.secondaryAliases()) {
+ crc.update(alias.getBytes(Charset.forName("UTF-8")));
+ Object prior = aliasIds.put(crc.getValue(), alias);
+ if (prior != null) {
+ throw new GeneralSecurityException("Two aliases
are being used that generate the same CRC-32 hash, please correct");
+ }
+ crc.reset();
+ }
+
+
crc.update(config.primaryAlias().getBytes(Charset.forName("UTF-8")));
+ primaryId = crc.getValue();
+ if (aliasIds.containsKey(primaryId)) {
+ throw new GeneralSecurityException(String.format("The
primary alias %s is either the same as or has the same CRC-32 hash as %s in the
secondary aliases, please
correct",config.primaryAlias(),aliasIds.get(primaryId)));
+ }
+
+ aliasIds.put(primaryId, config.primaryAlias());
+ crc.reset();
+ }
+
+ private byte[] toBytes(long value) {
+ return new byte[] { (byte) (value >>> 24), (byte) (value >>>
16), (byte) (value >>> 8), (byte) value };
+ }
+
+ @Override
+ public int getIdLength() {
+ return 4;
+ }
+
+ @Override
+ public byte[] getPrimaryKeyID() {
+ return toBytes(primaryId);
+ }
+
+ @Override
+ public Key getKey(byte[] id) throws GeneralSecurityException {
+ Long value = toLong(id);
+ String alias = aliasIds.get(value);
+ if (alias == null) {
+ if (!primaryId.equals(value)) {
+ throw new GeneralSecurityException("ID that was
provided does not match to any of the currently maintained aliases");
+ }
+ alias = config.primaryAlias();
+ }
+ return keystore.getKey(alias, config.password().toCharArray());
+ }
+
+ private Long toLong(byte[] bytes) {
+ long reply = 0;
+ for (byte b:bytes) {
+ reply = reply << 8;
+ reply = reply | (b & 0xff);
+ }
+ return reply;
+ }
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/OSGiKeyProvider.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/OSGiKeyProvider.java
new file mode 100644
index 0000000..f004b22
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/impl/OSGiKeyProvider.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.impl;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.zip.CRC32;
+
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.sling.resource.encryption.KeyProvider;
+import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.ConfigurationPolicy;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.AttributeType;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+import org.osgi.service.metatype.annotations.Option;
+
+@Component(immediate = true, property = { Constants.SERVICE_DESCRIPTION +
"=Sling Java Key Store Provisioner",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
+ KeyProvider.TYPE + "=OSGi" }, configurationPolicy =
ConfigurationPolicy.REQUIRE)
+@Designate(ocd = OSGiKeyProvider.Configuration.class)
+public class OSGiKeyProvider implements KeyProvider {
+
+ @ObjectClassDefinition(name = "Apache Sling Encryption Key Provider -
OSGi", description = "Apache Sling KeyProvider Implementation - OSGi")
+ public @interface Configuration {
+
+ @AttributeDefinition(name = "Key Algorithm", description =
"Algorithm used to generate the key",options = {@Option(label="AES",
value="AES") })
+ String keyAlgorithm() default "AES";
+
+ @AttributeDefinition(name = "Primary", description = "Base64
encoded primary key", type = AttributeType.PASSWORD)
+ String primaryAlias();
+
+ @AttributeDefinition(name = "Secondary", required = false,
description = "Base 64 encoded secondary keys", cardinality = Integer.MAX_VALUE)
+ String[] secondaryAliases() default {};
+
+ }
+
+
+ private Configuration config;
+
+ private HashMap<Long, String> aliasIds;
+
+ private Long primaryId;
+
+ @Activate
+ public void init(Configuration config) throws GeneralSecurityException,
IOException {
+ this.config = config;
+ // init keystore
+
+ aliasIds = new HashMap<>();
+ CRC32 crc = new CRC32();
+ String[] secondaryAlias = config.secondaryAliases();
+ if (secondaryAlias == null) {
+ secondaryAlias = new String[]{};
+ }
+ for (String alias : secondaryAlias) {
+ crc.update(alias.getBytes(Charset.forName("UTF-8")));
+ Object prior = aliasIds.put(crc.getValue() & 0xffff,
alias);
+ if (prior != null) {
+ throw new GeneralSecurityException("Two keys
are being used that generate the same CRC-32 hash, please correct");
+ }
+ crc.reset();
+ }
+
+
crc.update(config.primaryAlias().getBytes(Charset.forName("UTF-8")));
+ primaryId = crc.getValue() & 0xffff;
+ if (aliasIds.containsKey(primaryId)) {
+ throw new GeneralSecurityException(String.format("The
primary key %s is either the same as or has the same CRC-32 hash as %s in the
secondary keys, please correct",config.primaryAlias(),aliasIds.get(primaryId)));
+ }
+
+ aliasIds.put(primaryId, config.primaryAlias());
+ crc.reset();
+ }
+
+ private byte[] toBytes(long value) {
+ return new byte[] { (byte) (value >>> 24), (byte) (value >>>
16), (byte) (value >>> 8), (byte) value };
+ }
+
+ @Override
+ public int getIdLength() {
+ return 4;
+ }
+
+ @Override
+ public byte[] getPrimaryKeyID() {
+ return toBytes(primaryId);
+ }
+
+ @Override
+ public Key getKey(byte[] id) throws GeneralSecurityException {
+ Long value = toLong(id);
+ String alias = aliasIds.get(value);
+ if (alias == null) {
+ if (!primaryId.equals(value)) {
+ throw new GeneralSecurityException("ID that was
provided does not match to any of the currently maintained aliases");
+ }
+ alias = config.primaryAlias();
+ }
+ return new
SecretKeySpec(Base64.getDecoder().decode(alias.getBytes()),
config.keyAlgorithm());
+ }
+
+ private Long toLong(byte[] bytes) {
+ long reply = 0;
+ for (byte b:bytes) {
+ reply = reply << 8;
+ reply = reply | (b & 0xff);
+ }
+ return reply;
+ }
+
+}
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/package-info.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/package-info.java
new file mode 100644
index 0000000..d9ff438
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/package-info.java
@@ -0,0 +1,15 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
[email protected]("1.0")
+package org.apache.sling.resource.encryption;
\ No newline at end of file
diff --git
a/encrypt/src/main/java/org/apache/sling/resource/encryption/wrapper/EncryptableValueMapDecorator.java
b/encrypt/src/main/java/org/apache/sling/resource/encryption/wrapper/EncryptableValueMapDecorator.java
new file mode 100644
index 0000000..161e8d4
--- /dev/null
+++
b/encrypt/src/main/java/org/apache/sling/resource/encryption/wrapper/EncryptableValueMapDecorator.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption.wrapper;
+
+import java.util.Map;
+import java.util.stream.Stream;
+
+import javax.annotation.CheckForNull;
+
+import org.apache.sling.api.resource.ModifiableValueMap;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.wrappers.ModifiableValueMapDecorator;
+import org.apache.sling.resource.encryption.EncryptionException;
+import org.apache.sling.resource.encryption.EncryptionProvider;
+import org.apache.sling.resource.encryption.EncryptableValueMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The <code>EncryptionValueMap</code> is an easy way to encrypt and decrypt
+ * properties of a resource. With resources you can use
+ * {@link Resource#adaptTo()} to obtain a map that support encryption.
+ * <p>
+ *
+ * A <code>ValueMap</code> should be immutable.
+ */
+public class EncryptableValueMapDecorator extends ModifiableValueMapDecorator
+ implements ModifiableValueMap, EncryptableValueMap {
+
+ private EncryptionProvider ep;
+
+ /** Default logger. */
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ public EncryptableValueMapDecorator(Map<String, Object> base,
EncryptionProvider encryptionProvider) {
+ super(base);
+ ep = encryptionProvider;
+ }
+
+ /**
+ * Encrypts the value for this
+ *
+ * @param property
+ * property
+ */
+ @CheckForNull
+ public void encrypt(String property) {
+ super.put(property, doEncrypt(property, get(property)));
+ }
+
+ /**
+ * Sets a String property with the given name as being a non-encrypted
property.
+ * If a String value currently exists for the property and that value is
+ * currently encrypted, that value will be decrypted. Parameters that
are
+ * already decrypted will not change.
+ *
+ * @param property
+ * The name of the property
+ */
+ public void decrypt(String property) {
+ super.put(property, get(property));
+ };
+
+ @Override
+ public Object get(Object key) {
+ Object reply = super.get(key);
+ if (isEncrypted(reply)) {
+ return doDecrypt((String) key, reply);
+ }
+ return reply;
+ }
+
+ @Override
+ public Object put(String key, Object value) {
+ Object prior = super.put(key, value);
+ if (isEncrypted(prior)) {
+ super.put(key, doEncrypt(key, value));
+ return doDecrypt(key, prior);
+ }
+ return prior;
+ }
+
+ /**
+ * Method to encrypt an Object value.
+ *
+ * @param value
+ * to be encrypted
+ * @return the encrypted value
+ */
+ @SuppressWarnings("unchecked")
+ private <T> T doEncrypt(String property, T value) {
+ T reply = null;
+
+ if (value instanceof String) {
+ try {
+ reply = (T) ep.encrypt((String) value,
property);
+ } catch (EncryptionException e) {
+ logger.debug("unable to encrypt value {} of
property {}",value, property);
+ reply = value;
+ }
+ }
+
+ if (value instanceof String[]) {
+ reply = (T) Stream.of((String[]) value).map(string -> {
+ try {
+ return ep.encrypt(string, property);
+ } catch (EncryptionException e) {
+ logger.debug("unable to encrypt value
{} of property {}",string, property);
+ return string;
+ }
+ }).toArray(String[]::new);
+ }
+
+ return reply;
+ }
+
+ /**
+ * Decrypt the object
+ *
+ * @param value
+ * String representation of the encrypted value
+ * @return decrypted value
+ */
+ @SuppressWarnings("unchecked")
+ private <T> T doDecrypt(String property, T value) {
+ T reply = null;
+
+ if (value instanceof String) {
+ try {
+ reply = (T) ep.decrypt((String) value,
property);
+ } catch (EncryptionException e) {
+ logger.debug("unable to decrypt value {} of
property {}",value, property);
+ reply = value;
+ }
+ }
+
+ if (value instanceof String[]) {
+ reply = (T) Stream.of((String[]) value).map(string -> {
+ try {
+ return ep.decrypt(string, property);
+ } catch (EncryptionException e) {
+ logger.debug("unable to decrypt value
{} of property {}",string, property);
+ return string;
+ }
+ }).toArray(String[]::new);
+ }
+
+ return reply;
+ }
+
+ private boolean isEncrypted(Object value) {
+ if (value == null) {
+ return false;
+ }
+
+ if (value instanceof String) {
+ return ep.isEncrypted((String) value);
+ }
+
+ if (value instanceof String[]) {
+ String[] temp = (String[]) value;
+ if (temp.length > 0) {
+ return ep.isEncrypted(temp[0]);
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/encrypt/src/main/javacc/locator.jj
b/encrypt/src/main/javacc/locator.jj
new file mode 100644
index 0000000..da55735
--- /dev/null
+++ b/encrypt/src/main/javacc/locator.jj
@@ -0,0 +1,333 @@
+/*
+ * Copyright 2016 Jason E Bailey
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+options
+{
+ STATIC = false;
+ UNICODE_INPUT = true;
+}
+
+PARSER_BEGIN(Parser)
+package com.sas.sling.resource.parser;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import com.sas.sling.resource.parser.node.*;
+import com.sas.sling.resource.parser.predicates.*;
+
+public final class Parser
+{
+ private NodesFactory factory = new NodesFactory();
+
+}
+
+PARSER_END(Parser)
+
+SKIP :
+{
+ " "
+| "\t"
+}
+
+TOKEN :
+{
+ < #ALPHA : [ "a"-"z", "A"-"Z" ] >
+| < #ESCAPED_CHAR : "\\" ~[ ] >
+| < #DOT: "." >
+| < #PLUS: "+" >
+| < #MINUS: "-" >
+| < #DIGIT: [ "0"-"9" ] >
+| < #EXP: ["e","E"] ( < PLUS > | < MINUS > )? >
+}
+
+TOKEN :
+{
+ < UNRESERVED_STR : (~[ "\"", "'", "(", ")", ",", "=", "<", ">", " ", "[",
"]","+","-",".","0"-"9" ])+ >
+| < SINGLE_QUOTED_STR :
+ (
+ "'"
+ (
+ < ESCAPED_CHAR >
+ | ~[ "'", "\\" ]
+ )*
+ "'"
+ ) >
+| < DOUBLE_QUOTED_STR :
+ (
+ "\""
+ (
+ < ESCAPED_CHAR >
+ | ~[ "\"", "\\" ]
+ )*
+ "\""
+ ) >
+}
+
+TOKEN :
+{
+ < AND :
+ (
+ " && "
+ | " and "
+ ) >
+| < OR :
+ (
+ " || "
+ | " or "
+ ) >
+| < NULL : " null" >
+| < TRUE : " true" >
+| < FALSE : " false" >
+| < LPAREN : "(" >
+| < RPAREN : ")" >
+| < LBRACKET : "[" >
+| < RBRACKET : "]" >
+| < COMMA : "," >
+| < COMP :
+ (
+ ">"
+ | "<"
+ | "="
+ | "!"
+ | " in"
+ | " is"
+ | " less"
+ | " greater"
+ | " than"
+ | " like"
+ | " not"
+ | " contains"
+ | " any"
+ | " in"
+ )+ >
+}
+
+
+TOKEN: {
+ < NUMBER: <INTEGER> | <INTEGER> <FRACTIONAL_DIGITS> | <INTEGER>
<EXPONENT> | <INTEGER> <FRACTIONAL_DIGITS> <EXPONENT> >
+ | < INTEGER: (<MINUS>)? ( <DIGITS> ) > //support leading zeros
+ | < FRACTIONAL_DIGITS: <DOT> <DIGITS> >
+ | < EXPONENT: <EXP> <DIGITS> >
+ | < DIGITS: ( <DIGIT> )+ >
+}
+
+Node Input() :
+{
+ final Node node;
+}
+{
+ node = Or() < EOF >
+ {
+ return node;
+ }
+}
+
+Node Or() :
+{
+ final List < Node > nodes = new ArrayList < Node > (3);
+ Node node;
+}
+{
+ node = And()
+ {
+ nodes.add(node);
+ }
+ (
+ < OR > node = And()
+ {
+ nodes.add(node);
+ }
+ )*
+ {
+ return nodes.size() != 1 ? factory.createOrNode(nodes) : nodes.get(0);
+ }
+}
+
+Node And() :
+{
+ final List < Node > nodes = new ArrayList < Node > (3);
+ Node node;
+}
+{
+ node = Constraint()
+ {
+ nodes.add(node);
+ }
+ (
+ < AND > node = Constraint()
+ {
+ nodes.add(node);
+ }
+ )*
+ {
+ return nodes.size() != 1 ? factory.createAndNode(nodes) : nodes.get(0);
+ }
+}
+
+Node Constraint() :
+{
+ final Node node;
+}
+{
+ (
+ node = Group()
+ | node = Comparison()
+ )
+ {
+ return node;
+ }
+}
+
+Node Group() :
+{
+ final Node node;
+}
+{
+ < LPAREN > node = Or() < RPAREN >
+ {
+ return node;
+ }
+}
+
+Node Comparison() :
+{
+ Node leftValue;
+ Token op;
+ Node rightValue;
+}
+{
+ leftValue = Argument()
+ op = < COMP >
+ rightValue = Argument()
+ {
+ String comparison = op.image;
+ Optional<ComparisonOperator> oper =
ComparisonOperator.getSimpleOperator(comparison);
+ if (!oper.isPresent()) {
+ throw new TokenMgrError("'" + comparison + "' is not a valid
comparison", TokenMgrError.LEXICAL_ERROR);
+ }
+ return factory.createComparisonNode(oper.get(), leftValue, rightValue);
+ }
+}
+
+
+String Operator() :
+{}
+{
+ < COMP >
+ {
+ return token.image;
+ }
+}
+
+List < Node > Arguments() :
+{
+ Object value = new ArrayList();
+}
+{
+ (
+ < LPAREN > [ value = CommaSepArguments() ] < RPAREN >
+ )
+ {
+ return (List) value;
+ }
+|
+ value = Argument()
+ {
+ return Arrays.asList((Node) value);
+ }
+}
+
+List < Node > CommaSepArguments() :
+{
+ final List < Node > list = new ArrayList < Node > (3);
+ Node arg;
+}
+{
+ arg = Argument()
+ {
+ list.add(arg);
+ }
+ (
+ < COMMA >
+ arg = Argument()
+ {
+ list.add(arg);
+ }
+ )*
+ {
+ return list;
+ }
+}
+
+Node Argument() :
+{
+ Node selector = null;
+}
+{
+ (
+ selector = Literal()
+ | selector = Property()
+ | selector = Function()
+ )
+ {
+ return selector;
+ }
+}
+
+Node Function() :
+{
+ Node selector = null;
+ List < Node > children = null;
+}
+{
+ < UNRESERVED_STR >
+ {
+ selector = factory.createArgument(token.kind, token.image);
+ }
+ children = Arguments()
+ {
+ return factory.createFunction(selector, children);
+ }
+}
+
+Node Literal() :
+{
+}
+{
+ (
+ < DOUBLE_QUOTED_STR >
+ | < SINGLE_QUOTED_STR >
+ | < NUMBER >
+ | < NULL >
+ | < TRUE >
+ | < FALSE >
+ )
+ {
+ return factory.createArgument(token.kind, token.image);
+ }
+}
+
+Node Property() :
+{
+ Token string = null;
+}
+{
+ < LBRACKET > string = < UNRESERVED_STR > < RBRACKET >
+ {
+ return factory.createPropertySelector(string.image);
+ }
+}
diff --git
a/encrypt/src/test/java/org/apache/sling/resource/encryption/Base64EncryptionProvider.java
b/encrypt/src/test/java/org/apache/sling/resource/encryption/Base64EncryptionProvider.java
new file mode 100644
index 0000000..853e700
--- /dev/null
+++
b/encrypt/src/test/java/org/apache/sling/resource/encryption/Base64EncryptionProvider.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+
+public class Base64EncryptionProvider implements EncryptionProvider {
+
+ private static String ID = "|";
+
+ @Override
+ public byte[] encrypt(byte[] toEncode, byte[] aad) throws
EncryptionException {
+ return Base64.getEncoder().encode(toEncode);
+ }
+
+ @Override
+ public byte[] decrypt(byte[] toDecode, byte[] aad) throws
EncryptionException {
+ return Base64.getDecoder().decode(toDecode);
+ }
+
+ @Override
+ public String encrypt(String toEncode, String aad) throws
EncryptionException {
+ try {
+ return ID + new
String(encrypt(toEncode.getBytes("UTF-8"), aad.getBytes("UTF-8")),"UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ throw new EncryptionException(e);
+ }
+ }
+
+ @Override
+ public String decrypt(String toDecode, String aad) throws
EncryptionException {
+ try {
+ return new
String(decrypt(toDecode.substring(1).getBytes("UTF-8"),
aad.getBytes("UTF-8")),"UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ throw new EncryptionException(e);
+ }
+ }
+
+ @Override
+ public boolean isEncrypted(String property) {
+ return property.startsWith(ID);
+ }
+
+}
diff --git
a/encrypt/src/test/java/org/apache/sling/resource/encryption/BaseEncryptionTest.java
b/encrypt/src/test/java/org/apache/sling/resource/encryption/BaseEncryptionTest.java
new file mode 100644
index 0000000..a9bfb42
--- /dev/null
+++
b/encrypt/src/test/java/org/apache/sling/resource/encryption/BaseEncryptionTest.java
@@ -0,0 +1,202 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+
+import javax.crypto.NoSuchPaddingException;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ValueMap;
+import
org.apache.sling.resource.encryption.impl.EncryptableValueMapAdapterFactory;
+import org.apache.sling.testing.mock.sling.junit.SlingContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class BaseEncryptionTest {
+
+ @Rule
+ public final SlingContext context = new SlingContext();
+
+ private static String START_PATH = "/content/sample/en";
+
+ private static String ARRAY_PATH =
"/content/sample/en/testpage1/jcr:content";
+
+ String encryptedProperty;
+
+ @SuppressWarnings("serial")
+ @Before
+ public void setUp()
+ throws IOException,GeneralSecurityException {
+ context.load().json("/data.json", START_PATH);
+ EncryptionProvider cipherProvider = new
Base64EncryptionProvider();
+ context.registerService(EncryptionProvider.class,
cipherProvider);
+ EncryptableValueMapAdapterFactory factory = new
EncryptableValueMapAdapterFactory();
+ injectCipherProvider(factory, cipherProvider);
+ context.registerService(AdapterFactory.class, factory, new
HashMap<String, Object>() {
+ {
+ put(AdapterFactory.ADAPTABLE_CLASSES, new
String[] { Resource.class.getName() });
+ put(AdapterFactory.ADAPTER_CLASSES, new
String[] { EncryptableValueMap.class.getName() });
+ }
+ });
+
+ this.encryptedProperty = "bar";
+ }
+
+ private void injectCipherProvider(EncryptableValueMapAdapterFactory
factory, EncryptionProvider cipherProvider) {
+ Class<?> resolverClass = factory.getClass();
+ java.lang.reflect.Field resolverField;
+ try {
+ resolverField =
resolverClass.getDeclaredField("encryptionProvider");
+ resolverField.setAccessible(true);
+ resolverField.set(factory, cipherProvider);
+ } catch (NoSuchFieldException | SecurityException |
IllegalArgumentException | IllegalAccessException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Tests initial access to the EncryptionProvider and that the test
provider
+ * returns expected results Cipher classes
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testCipherProvider()
+ throws Exception {
+ EncryptionProvider cipher =
context.getService(EncryptionProvider.class);
+ assertNotNull(cipher);
+
+ String encrypted = cipher.encrypt(START_PATH, "foo");
+ assertNotEquals(START_PATH, encrypted);
+ String decoded = cipher.decrypt(encrypted, "foo");
+ assertEquals(START_PATH, decoded);
+ }
+
+ /**
+ * Tests encryption and decryption of a String value
+ *
+ */
+ @Test
+ public void testUnencryptedString() {
+ Resource resource =
context.resourceResolver().getResource(START_PATH);
+
+ ValueMap map = resource.adaptTo(ValueMap.class);
+ EncryptableValueMap encrytionMap =
resource.adaptTo(EncryptableValueMap.class);
+
+ String property = "jcr:primaryType";
+
+ // get original value
+ String value = encrytionMap.get(property, String.class);
+ assertEquals("app:Page", value);
+
+ // encrypt property and validate property appears to be the same
+ encrytionMap.encrypt(property);
+ value = encrytionMap.get(property, String.class);
+ assertEquals("app:Page", value);
+
+ // validate the underlying value is encrypted
+ value = map.get(property, "fail");
+ assertNotEquals("app:Page", value);
+ assertNotEquals("fail", value);
+
+ // decrypt property and validate the underlying map is back to
normal
+ encrytionMap.decrypt(property);
+ value = map.get(property, String.class);
+ assertEquals("app:Page", value);
+ }
+
+ /**
+ * Tests Encodind and Decoding of an array of String values
+ *
+ * @throws NoSuchPaddingException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ @Test
+ public void testArrayofValues() {
+ Resource resource =
context.resourceResolver().getResource(ARRAY_PATH);
+
+ ValueMap map = resource.adaptTo(ValueMap.class);
+ EncryptableValueMap encrytionMap =
resource.adaptTo(EncryptableValueMap.class);
+
+ String property = "foo";
+
+ // get original values
+ String[] value = encrytionMap.get(property, String[].class);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+
+ // encrypt property and verifies it looks good
+ encrytionMap.encrypt(property);
+ value = encrytionMap.get(property, String[].class);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+
+ //verify underlying map is encrypted
+ value = map.get(property, String[].class);
+ assertNotEquals("foo", value[0]);
+ assertNotEquals("dog", value[1]);
+
+ //decrypt the property and validate
+ encrytionMap.decrypt(property);
+ value = encrytionMap.get(property, String[].class);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+
+ //verify underlying map is decrypted
+ value = map.get(property, String[].class);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+
+ }
+
+ /**
+ * Tests the decryption and handling of pre-existing values
+ *
+ * @throws NoSuchPaddingException
+ * @throws NoSuchAlgorithmException
+ * @throws InvalidKeyException
+ */
+ @Test
+ public void testPreEncryptedArrayofValues() {
+ Resource resource =
context.resourceResolver().getResource(ARRAY_PATH);
+
+ ValueMap map = resource.adaptTo(ValueMap.class);
+ EncryptableValueMap encryptionMap =
resource.adaptTo(EncryptableValueMap.class);
+
+ // verify original is encrypted
+ String[] value = map.get(encryptedProperty, String[].class);
+ assertNotEquals("foo", value[0]);
+ assertNotEquals("dog", value[1]);
+
+ // get decrypted values and validate
+ value = (String[]) encryptionMap.get(encryptedProperty);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+
+ //decrypt pre-encrypted properties
+ encryptionMap.decrypt(encryptedProperty);
+ value = (String[]) map.get(encryptedProperty);
+ assertArrayEquals(new String[] { "foo", "dog" }, value);
+ }
+
+}
diff --git
a/encrypt/src/test/java/org/apache/sling/resource/encryption/Create.java
b/encrypt/src/test/java/org/apache/sling/resource/encryption/Create.java
new file mode 100644
index 0000000..a22381f
--- /dev/null
+++ b/encrypt/src/test/java/org/apache/sling/resource/encryption/Create.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Utility for the creation of the keystore used by junit
+ *
+ */
+public class Create {
+
+ private static String KEY_ALGORITHM = "AES";
+
+ public static void main(String[] args) throws GeneralSecurityException,
IOException {
+ KeyStore ks = KeyStore.getInstance("JCEKS");
+ ks.load(null);
+ char[] password = "secret".toCharArray();
+ ks.setKeyEntry("old",
getCipher1(),password,(Certificate[])null);
+ ks.setKeyEntry("new",
getCipher2(),password,(Certificate[])null);
+ FileOutputStream writeStream = new
FileOutputStream("./src/test/resources/keystore.jks");
+ ks.store(writeStream, password);
+ writeStream.close();
+ System.out.println(new File("./keystore").getAbsolutePath());
+ }
+
+ private static Key getCipher1() throws GeneralSecurityException {
+ return new SecretKeySpec("passwordpassword".getBytes(),
KEY_ALGORITHM);
+ }
+
+ private static Key getCipher2() throws GeneralSecurityException {
+ return new SecretKeySpec("password2passwor".getBytes(),
KEY_ALGORITHM);
+ }
+
+}
diff --git
a/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionKeyStoreTest.java
b/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionKeyStoreTest.java
new file mode 100644
index 0000000..d584358
--- /dev/null
+++
b/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionKeyStoreTest.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.security.GeneralSecurityException;
+import java.util.HashMap;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.resource.ModifiableValueMap;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.resource.encryption.impl.AesGcmEncryptionProvider;
+import
org.apache.sling.resource.encryption.impl.AesGcmEncryptionProvider.Configuration;
+import org.apache.sling.resource.encryption.impl.JCEKSKeyProvider;
+import
org.apache.sling.resource.encryption.wrapper.EncryptableValueMapDecorator;
+import org.junit.Before;
+
+public class EncryptionKeyStoreTest extends BaseEncryptionTest {
+
+ private static String START_PATH = "/content/sample/en";
+
+ @SuppressWarnings("serial")
+ @Before
+ public synchronized void setUp()
+ throws GeneralSecurityException, IOException {
+
+ context.load().json("/data2.json", START_PATH);
+
+ JCEKSKeyProvider kp = new JCEKSKeyProvider();
+ kp.init(getConfig());
+
+ AesGcmEncryptionProvider encryptionProvider = new
AesGcmEncryptionProvider();
+ injectKeyProvider(encryptionProvider, kp);
+ encryptionProvider.init(new Configuration() {
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String keyProvider_target() {
+ return null;
+ }
+
+ @Override
+ public String encryptionPrefix() {
+ return "\uD83D\uDD12";
+ }
+ });
+
+ context.registerService(EncryptionProvider.class,
encryptionProvider);
+
+
+ context.registerService(AdapterFactory.class,
adapterFactory(encryptionProvider), new HashMap<String, Object>() {
+ {
+ put(AdapterFactory.ADAPTABLE_CLASSES, new
String[] { Resource.class.getName() });
+ put(AdapterFactory.ADAPTER_CLASSES, new
String[] { EncryptableValueMap.class.getName() });
+ }
+ });
+ this.encryptedProperty = "bar";
+ }
+
+ private AdapterFactory adapterFactory(EncryptionProvider ep) {
+ return new AdapterFactory() {
+ @SuppressWarnings("unchecked")
+ public <AdapterType> AdapterType getAdapter(Object
adaptable, Class<AdapterType> type) {
+ ValueMap map = ((Resource)
adaptable).adaptTo(ModifiableValueMap.class);
+ if (map == null) {
+ map = ((Resource)
adaptable).adaptTo(ValueMap.class);
+ }
+ return (AdapterType) new
EncryptableValueMapDecorator(map, ep);
+ }
+ };
+ }
+
+ private void injectKeyProvider(EncryptionProvider ep, KeyProvider key) {
+ Class<?> resolverClass = ep.getClass();
+ java.lang.reflect.Field resolverField;
+ try {
+ resolverField =
resolverClass.getDeclaredField("keyProvider");
+ resolverField.setAccessible(true);
+ resolverField.set(ep, key);
+ } catch (NoSuchFieldException | SecurityException |
IllegalArgumentException | IllegalAccessException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private JCEKSKeyProvider.Configuration getConfig(){
+ return new JCEKSKeyProvider.Configuration() {
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String path() {
+ return "./src/test/resources/keystore.jks";
+ }
+
+ @Override
+ public String password() {
+ return "secret";
+ }
+
+ @Override
+ public String primaryAlias() {
+ return "new";
+ }
+
+ @Override
+ public String[] secondaryAliases() {
+ return new String[] {"old"};
+ }};
+ }
+}
diff --git
a/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionOSGiStoreTest.java
b/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionOSGiStoreTest.java
new file mode 100644
index 0000000..4a6308c
--- /dev/null
+++
b/encrypt/src/test/java/org/apache/sling/resource/encryption/EncryptionOSGiStoreTest.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sling.resource.encryption;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.security.GeneralSecurityException;
+import java.util.HashMap;
+
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.resource.ModifiableValueMap;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.resource.encryption.impl.AesGcmEncryptionProvider;
+import
org.apache.sling.resource.encryption.impl.AesGcmEncryptionProvider.Configuration;
+import org.apache.sling.resource.encryption.impl.OSGiKeyProvider;
+import
org.apache.sling.resource.encryption.wrapper.EncryptableValueMapDecorator;
+import org.junit.Before;
+
+public class EncryptionOSGiStoreTest extends BaseEncryptionTest {
+
+ private static String START_PATH = "/content/sample/en";
+
+ @SuppressWarnings("serial")
+ @Before
+ public synchronized void setUp() {
+
+ context.load().json("/data3.json", START_PATH);
+ AesGcmEncryptionProvider encryptionProvider = new
AesGcmEncryptionProvider();
+ OSGiKeyProvider kp = new OSGiKeyProvider();
+ try {
+
+ kp.init(getConfig());
+
+ injectKeyProvider(encryptionProvider, kp);
+ encryptionProvider.init(new Configuration() {
+
+ @Override
+ public Class<? extends Annotation>
annotationType() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String keyProvider_target() {
+ return null;
+ }
+
+ @Override
+ public String encryptionPrefix() {
+ return "\uD83D\uDD12";
+ }
+ });
+
+ } catch (NullPointerException | GeneralSecurityException |
IOException e) {
+ assertTrue(false);
+ }
+ context.registerService(EncryptionProvider.class,
encryptionProvider);
+
+ context.registerService(AdapterFactory.class,
adapterFactory(encryptionProvider),
+ new HashMap<String, Object>() {
+ {
+
put(AdapterFactory.ADAPTABLE_CLASSES, new String[] { Resource.class.getName()
});
+
put(AdapterFactory.ADAPTER_CLASSES, new String[] {
EncryptableValueMap.class.getName() });
+ }
+ });
+ this.encryptedProperty = "cat";
+ }
+
+ private AdapterFactory adapterFactory(EncryptionProvider ep) {
+ return new AdapterFactory() {
+ @SuppressWarnings("unchecked")
+ public <AdapterType> AdapterType getAdapter(Object
adaptable, Class<AdapterType> type) {
+ ValueMap map = ((Resource)
adaptable).adaptTo(ModifiableValueMap.class);
+ if (map == null) {
+ map = ((Resource)
adaptable).adaptTo(ValueMap.class);
+ }
+ return (AdapterType) new
EncryptableValueMapDecorator(map, ep);
+ }
+ };
+ }
+
+ private void injectKeyProvider(EncryptionProvider ep, KeyProvider key) {
+ Class<?> resolverClass = ep.getClass();
+ java.lang.reflect.Field resolverField;
+ try {
+ resolverField =
resolverClass.getDeclaredField("keyProvider");
+ resolverField.setAccessible(true);
+ resolverField.set(ep, key);
+ } catch (NoSuchFieldException | SecurityException |
IllegalArgumentException | IllegalAccessException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private OSGiKeyProvider.Configuration getConfig() {
+ return new OSGiKeyProvider.Configuration() {
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String keyAlgorithm() {
+ return "AES";
+ }
+
+ @Override
+ public String primaryAlias() {
+ return "cGFzc3dvcmRwYXNzd29yZA==";
+ }
+
+ @Override
+ public String[] secondaryAliases() {
+ return new String[] {};
+ }
+ };
+ }
+}
diff --git a/encrypt/src/test/resources/data.json
b/encrypt/src/test/resources/data.json
new file mode 100644
index 0000000..7a27d92
--- /dev/null
+++ b/encrypt/src/test/resources/data.json
@@ -0,0 +1,17 @@
+{
+ "jcr:primaryType": "app:Page",
+ "reallyExceedinglyLongPropertyNameThatIsGreaterThan16bytes":"workswell",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English"
+ },
+ "testpage1": {
+ "jcr:primaryType": "app:Page",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English",
+ "foo": ["foo", "dog"],
+ "bar": ["|Zm9v", "|ZG9n"]
+ }
+ }
+}
\ No newline at end of file
diff --git a/encrypt/src/test/resources/data2.json
b/encrypt/src/test/resources/data2.json
new file mode 100644
index 0000000..9a35940
--- /dev/null
+++ b/encrypt/src/test/resources/data2.json
@@ -0,0 +1,17 @@
+{
+ "jcr:primaryType": "app:Page",
+ "reallyExceedinglyLongPropertyNameThatIsGreaterThan16bytes":"workswell",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English"
+ },
+ "testpage1": {
+ "jcr:primaryType": "app:Page",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English",
+ "foo": ["foo", "dog"],
+ "bar":
["\uD83D\uDD122u7G5DT0uPXQ1606a+NERe9EVtuH6PR31MO7FjN4NZw+KKc=",
"\uD83D\uDD12zCjPz1RunLoYCpuJa+NERSbI0/XQUmrofL8ybD0+nCD1IWU="]
+ }
+ }
+}
\ No newline at end of file
diff --git a/encrypt/src/test/resources/data3.json
b/encrypt/src/test/resources/data3.json
new file mode 100644
index 0000000..64b7828
--- /dev/null
+++ b/encrypt/src/test/resources/data3.json
@@ -0,0 +1,17 @@
+{
+ "jcr:primaryType": "app:Page",
+ "reallyExceedinglyLongPropertyNameThatIsGreaterThan16bytes":"workswell",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English"
+ },
+ "testpage1": {
+ "jcr:primaryType": "app:Page",
+ "jcr:content": {
+ "jcr:primaryType": "app:PageContent",
+ "jcr:title": "English",
+ "foo": ["foo", "dog"],
+ "cat":
["\uD83D\uDD12e8V6V+7Le8urIWn+AABmMJ8vlAZD6x+f8qe+OHElxx3n3PE=",
"\uD83D\uDD12/oUzkTDHAckDVHFIAABmMCo4rmZs2Z5W3j3XSjWAUENCaLk="]
+ }
+ }
+}
\ No newline at end of file
diff --git a/encrypt/src/test/resources/keystore.jks
b/encrypt/src/test/resources/keystore.jks
new file mode 100644
index 0000000..8d87a65
Binary files /dev/null and b/encrypt/src/test/resources/keystore.jks differ
--
To stop receiving notification emails like this one, please contact
['"[email protected]" <[email protected]>'].