diff --git a/.gitignore b/.gitignore index 08614653abf05e7791be95e1b6bf9d24ee1160da..48aeabab011c30893aff2546cc4134e8b20a59d3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,9 @@ *.tulsiconf-user tulsi-* tulsigen-* +*.iml +.gradle +**/local.properties +**/build +.externalNativeBuild + diff --git a/README.md b/README.md index 6dfbad70114ea58b363a042bc4951e212c0c3b99..e516d93039bd697e3445e0a75f216142250d4ef3 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,8 @@ development. **TIP** The easiest way to get started with Tink is to install [Bazel](https://docs.bazel.build/versions/master/install.html), then build, run -and study the -[`helloworld`](https://github.com/thaidn/tink-examples/tree/master/helloworld) -example. +and study the [`hello world samples`] +(https://github.com/google/tink/tree/master/examples/helloworld). Tink performs cryptographic tasks via so-called [primitives](doc/PRIMITIVES.md), each of which is defined via a corresponding interface that specifies the diff --git a/examples/BUILD b/examples/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..f631b6df06d13b4ecf09aed3d810f02b996f197e --- /dev/null +++ b/examples/BUILD @@ -0,0 +1,3 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) # Apache 2.0 diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..871e66fd0320ab4389bf981464f9ce28c430a405 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,15 @@ +# tink-examples + +These examples show how to use [Tink](https://github.com/google/tink) +to perform common crypto tasks. They also show how to add a dependency +on Tink using Maven, Gradle or Bazel. + +These examples share with Tink the same Bazel's WORKSPACE, thus their +BUILD files can directly depend on Tink. There are also other examples +in [the tink-examples repo](https://github.com/thaidn/tink-examples) +that show how to add Tink as a dependency using Bazel's maven_jar rule. + +Subscribe to our +[mailing list](https://groups.google.com/forum/#!forum/tink-users) if you +have any questions. To join, simply send an empty email to +`tink-users+subscribe@googlegroups.com`. diff --git a/examples/helloworld/android/README.md b/examples/helloworld/android/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2a31934c2b1223276131b38e24b0040495cd8af5 --- /dev/null +++ b/examples/helloworld/android/README.md @@ -0,0 +1,13 @@ +# Android Hello World + +This is a simple app that allows encrypting and decrypting strings +with keys stored in private shared preferences. On Android M or newer +the keys are further encrypted with a master key stored in Android +Keystore. + +It demonstrates the basic steps of using Tink, namely generating or +loading key material, obtaining a primitive, and using the primitive +to do crypto. It also shows how one can add a dependency on Tink +using Gradle. + +The easiest way to build this app is to import it to Android Studio. diff --git a/examples/helloworld/android/app/build.gradle b/examples/helloworld/android/app/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..826826e869582f3aa4c86730b758d426b97d8ca4 --- /dev/null +++ b/examples/helloworld/android/app/build.gradle @@ -0,0 +1,35 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 26 + buildToolsVersion "26.0.1" + defaultConfig { + applicationId "com.helloworld" + minSdkVersion 14 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { + exclude group: 'com.android.support', module: 'support-annotations' + // This is already included in Tink. + exclude group: 'com.google.code.findbugs' + }) + compile 'com.android.support:appcompat-v7:26.+' + compile 'com.android.support:design:26.+' + testCompile 'junit:junit:4.12' + + // Tink 1.0.0 for Android. + compile 'com.google.crypto.tink:tink-android:1.0.0' +} diff --git a/examples/helloworld/android/app/src/main/AndroidManifest.xml b/examples/helloworld/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..cd66328dec34f9970a5c5d4fa1b1212e63aaa1ad --- /dev/null +++ b/examples/helloworld/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.helloworld"> + + <!-- To auto-complete the email text field in the login form with the user's emails --> + + <application + android:name=".TinkApplication" + android:allowBackup="true" + android:icon="@mipmap/ic_launcher" + android:label="@string/app_name" + android:roundIcon="@mipmap/ic_launcher_round" + android:supportsRtl="true" + android:theme="@style/AppTheme"> + <activity + android:name=".MainActivity" + android:label="@string/app_name"> + <intent-filter> + <action android:name="android.intent.action.MAIN" /> + + <category android:name="android.intent.category.LAUNCHER" /> + </intent-filter> + </activity> + </application> + +</manifest> \ No newline at end of file diff --git a/examples/helloworld/android/app/src/main/java/com/helloworld/MainActivity.java b/examples/helloworld/android/app/src/main/java/com/helloworld/MainActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..6ed2b1dd237a7b2f7554bf4815abf8ee3daa0c2a --- /dev/null +++ b/examples/helloworld/android/app/src/main/java/com/helloworld/MainActivity.java @@ -0,0 +1,86 @@ +package com.helloworld; + +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.util.Base64; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.EditText; +import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; + +public class MainActivity extends AppCompatActivity { + private static final byte[] EMPTY_ASSOCIATED_DATA = new byte[0]; + + private TinkApplication mApplication; + private EditText mPlaintextView; + private EditText mCiphertextView; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + mApplication = (TinkApplication) getApplicationContext(); + + mPlaintextView = (EditText) findViewById(R.id.plaintext); + mCiphertextView = (EditText) findViewById(R.id.ciphertext); + Button mEncryptButton = (Button) findViewById(R.id.encrypt_button); + mEncryptButton.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + attemptEncrypt(); + } + }); + Button mDecryptButton = (Button) findViewById(R.id.decrypt_button); + mDecryptButton.setOnClickListener( + new OnClickListener() { + @Override + public void onClick(View view) { + attemptDecrypt(); + } + }); + } + + private void attemptEncrypt() { + mPlaintextView.setError(null); + mCiphertextView.setError(null); + mCiphertextView.setText(""); + + try { + byte[] plaintext = mPlaintextView.getText().toString().getBytes("UTF-8"); + byte[] ciphertext = mApplication.aead.encrypt(plaintext, EMPTY_ASSOCIATED_DATA); + mCiphertextView.setText(base64Encode(ciphertext)); + } catch (UnsupportedEncodingException | GeneralSecurityException | IllegalArgumentException e) { + mCiphertextView.setError( + String.format("%s: %s", getString(R.string.error_cannot_encrypt), e.toString())); + mPlaintextView.requestFocus(); + } + } + + private void attemptDecrypt() { + mPlaintextView.setError(null); + mPlaintextView.setText(""); + mCiphertextView.setError(null); + + try { + byte[] ciphertext = base64Decode(mCiphertextView.getText().toString()); + byte[] plaintext = mApplication.aead.decrypt(ciphertext, EMPTY_ASSOCIATED_DATA); + mPlaintextView.setText(new String(plaintext, "UTF-8")); + } catch (UnsupportedEncodingException | GeneralSecurityException | IllegalArgumentException e) { + mPlaintextView.setError( + String.format("%s: %s", getString(R.string.error_cannot_decrypt), e.toString())); + mCiphertextView.requestFocus(); + } + } + + private static String base64Encode(final byte[] input) { + return Base64.encodeToString(input, Base64.DEFAULT); + } + + private static byte[] base64Decode(String input) { + return Base64.decode(input, Base64.DEFAULT); + } +} diff --git a/examples/helloworld/android/app/src/main/java/com/helloworld/TinkApplication.java b/examples/helloworld/android/app/src/main/java/com/helloworld/TinkApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..ebafa7070a50eacb679c8901a1a38dc35ba58475 --- /dev/null +++ b/examples/helloworld/android/app/src/main/java/com/helloworld/TinkApplication.java @@ -0,0 +1,41 @@ +package com.helloworld; + +import android.app.Application; +import com.google.crypto.tink.Aead; +import com.google.crypto.tink.Config; +import com.google.crypto.tink.KeysetHandle; +import com.google.crypto.tink.aead.AeadFactory; +import com.google.crypto.tink.aead.AeadKeyTemplates; +import com.google.crypto.tink.config.TinkConfig; +import com.google.crypto.tink.integration.android.AndroidKeysetManager; +import java.io.IOException; +import java.security.GeneralSecurityException; + +/** A custom application that initializes the Tink runtime at application startup. */ +public class TinkApplication extends Application { + private static final String TAG = TinkApplication.class.toString(); + private static final String PREF_FILE_NAME = "hello_world_pref"; + private static final String TINK_KEYSET_NAME = "hello_world_keyset"; + private static final String MASTER_KEY_URI = "android-keystore://hello_world_master_key"; + public Aead aead; + + @Override + public final void onCreate() { + super.onCreate(); + try { + Config.register(TinkConfig.TINK_1_0_0); + aead = AeadFactory.getPrimitive(getOrGenerateNewKeysetHandle()); + } catch (GeneralSecurityException | IOException e) { + throw new RuntimeException(e); + } + } + + private KeysetHandle getOrGenerateNewKeysetHandle() throws IOException, GeneralSecurityException { + return new AndroidKeysetManager.Builder() + .withSharedPref(getApplicationContext(), TINK_KEYSET_NAME, PREF_FILE_NAME) + .withKeyTemplate(AeadKeyTemplates.AES256_GCM) + .withMasterKeyUri(MASTER_KEY_URI) + .build() + .getKeysetHandle(); + } +} diff --git a/examples/helloworld/android/app/src/main/res/layout/activity_main.xml b/examples/helloworld/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000000000000000000000000000000000000..263ac6f41420c5ae01d4f6794b5b1652f2d4ae0e --- /dev/null +++ b/examples/helloworld/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,74 @@ +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:gravity="center_horizontal" + android:orientation="vertical" + android:paddingBottom="@dimen/activity_vertical_margin" + android:paddingLeft="@dimen/activity_horizontal_margin" + android:paddingRight="@dimen/activity_horizontal_margin" + android:paddingTop="@dimen/activity_vertical_margin" + tools:context="com.helloworld.MainActivity"> + + <ScrollView + android:id="@+id/login_form" + android:layout_width="match_parent" + android:layout_height="match_parent"> + + <LinearLayout + android:id="@+id/email_login_form" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="vertical"> + + <android.support.design.widget.TextInputLayout + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <EditText + android:id="@+id/plaintext" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:hint="@string/prompt_plaintext" + android:inputType="textMultiLine" + android:lines="3" + android:minLines="3" + android:maxLines="10" /> + + </android.support.design.widget.TextInputLayout> + + <android.support.design.widget.TextInputLayout + android:layout_width="match_parent" + android:layout_height="wrap_content"> + + <EditText + android:id="@+id/ciphertext" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:hint="@string/prompt_ciphertext" + android:inputType="textMultiLine" + android:lines="3" + android:minLines="3" + android:maxLines="10" /> + + </android.support.design.widget.TextInputLayout> + + <Button + android:id="@+id/encrypt_button" + style="?android:textAppearanceSmall" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="@string/action_encrypt" + android:textStyle="bold" /> + + <Button + android:id="@+id/decrypt_button" + style="?android:textAppearanceSmall" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:text="@string/action_decrypt" + android:textStyle="bold" /> + + </LinearLayout> + </ScrollView> +</LinearLayout> diff --git a/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..cde69bcccec65160d92116f20ffce4fce0b5245c Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..9a078e3e1a42d474c78470a73c7987cf7ac5d9a0 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..c133a0cbd379f5af6dbf1a899a0293ca5eccfad0 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..efc028a636dd690a51db5a525cf781a5a7daba68 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..bfa42f0e7b91d006d22352c9ff2f134e504e3c1d Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..3af2608a4492ef9ae63a77ec3305aedda89594cb Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..324e72cdd7480cb983fa1bcc7ce686e51ef87fe7 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..9bec2e623103ac9713b00cad8502a057c1efda61 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..aee44e138434630332d88b1680f33c4b24c70ab3 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..34947cd6bbf9c729be83edc96ad08a1d42b82bc9 Binary files /dev/null and b/examples/helloworld/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/examples/helloworld/android/app/src/main/res/values/colors.xml b/examples/helloworld/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000000000000000000000000000000000000..3ab3e9cbce07f7cdc941fc8ba424c05e83ed80f0 --- /dev/null +++ b/examples/helloworld/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<resources> + <color name="colorPrimary">#3F51B5</color> + <color name="colorPrimaryDark">#303F9F</color> + <color name="colorAccent">#FF4081</color> +</resources> diff --git a/examples/helloworld/android/app/src/main/res/values/dimens.xml b/examples/helloworld/android/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000000000000000000000000000000000000..47c82246738c4d056e8030d3a259206f42e8e15d --- /dev/null +++ b/examples/helloworld/android/app/src/main/res/values/dimens.xml @@ -0,0 +1,5 @@ +<resources> + <!-- Default screen margins, per the Android Design guidelines. --> + <dimen name="activity_horizontal_margin">16dp</dimen> + <dimen name="activity_vertical_margin">16dp</dimen> +</resources> diff --git a/examples/helloworld/android/app/src/main/res/values/strings.xml b/examples/helloworld/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000000000000000000000000000000000..e222d50808b6a5441e8c7147048e428650b3637f --- /dev/null +++ b/examples/helloworld/android/app/src/main/res/values/strings.xml @@ -0,0 +1,12 @@ +<resources> + <string name="app_name">Tink Hello World</string> + + <!-- Strings related to login --> + <string name="prompt_plaintext">Plaintext</string> + <string name="prompt_ciphertext">Ciphertext</string> + <string name="action_encrypt">Encrypt</string> + <string name="action_decrypt">Decrypt</string> + <string name="error_cannot_encrypt">Cannot encrypt</string> + <string name="error_cannot_decrypt">Cannot decrypt</string> + <string name="error_field_required">This field is required</string> +</resources> diff --git a/examples/helloworld/android/app/src/main/res/values/styles.xml b/examples/helloworld/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000000000000000000000000000000000000..5885930df6d10edf3d6df40d6556297d11f953da --- /dev/null +++ b/examples/helloworld/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ +<resources> + + <!-- Base application theme. --> + <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> + <!-- Customize your theme here. --> + <item name="colorPrimary">@color/colorPrimary</item> + <item name="colorPrimaryDark">@color/colorPrimaryDark</item> + <item name="colorAccent">@color/colorAccent</item> + </style> + +</resources> diff --git a/examples/helloworld/android/build.gradle b/examples/helloworld/android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..c2eea8e27fd12cc1e274a0940f06f350e855e20f --- /dev/null +++ b/examples/helloworld/android/build.gradle @@ -0,0 +1,23 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.3' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/examples/helloworld/android/gradle.properties b/examples/helloworld/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..aac7c9b4614ccfde6c721f24994cf30885a791d0 --- /dev/null +++ b/examples/helloworld/android/gradle.properties @@ -0,0 +1,17 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/examples/helloworld/android/gradle/wrapper/gradle-wrapper.jar b/examples/helloworld/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..13372aef5e24af05341d49695ee84e5f9b594659 Binary files /dev/null and b/examples/helloworld/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/helloworld/android/gradle/wrapper/gradle-wrapper.properties b/examples/helloworld/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..fe9cb0bd080eda9a90166b15fa2274503abe3421 --- /dev/null +++ b/examples/helloworld/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Sep 18 16:34:03 PDT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip diff --git a/examples/helloworld/android/gradlew b/examples/helloworld/android/gradlew new file mode 100755 index 0000000000000000000000000000000000000000..9d82f78915133e1c35a6ea51252590fb38efac2f --- /dev/null +++ b/examples/helloworld/android/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/examples/helloworld/android/gradlew.bat b/examples/helloworld/android/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..aec99730b4e8fcd90b57a0e8e01544fea7c31a89 --- /dev/null +++ b/examples/helloworld/android/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/helloworld/android/settings.gradle b/examples/helloworld/android/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..e7b4def49cb53d9aa04228dd3edb14c9e635e003 --- /dev/null +++ b/examples/helloworld/android/settings.gradle @@ -0,0 +1 @@ +include ':app' diff --git a/examples/helloworld/java/BUILD b/examples/helloworld/java/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..d96bd80783a614562de490b01b37987226afb04b --- /dev/null +++ b/examples/helloworld/java/BUILD @@ -0,0 +1,21 @@ +package(default_visibility = ["//visibility:public"]) + +licenses(["notice"]) # Apache 2.0 + +java_binary( + name = "helloworld", + srcs = glob([ + "src/main/**/*.java", + ]), + main_class = "com.helloworld.HelloWorld", + runtime_deps = [ + "@com_google_protobuf_java//:protobuf_java", + "@org_json_json//jar", + ], + deps = [ + "//java", + "//java:cleartext_keyset_handle", + "//java:subtle", + "@args4j//jar", + ], +) diff --git a/examples/helloworld/java/README.md b/examples/helloworld/java/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5997599906a88dcf021ab28a2faf8f1342f8c07d --- /dev/null +++ b/examples/helloworld/java/README.md @@ -0,0 +1,42 @@ +# Java Hello World + +This is a command-line tool that can encrypt and decrypt small files with +AES128-GCM. + +It demonstrates the basic steps of using Tink, namely generating or loading +key material, obtaining a primitive, and using the primitive to do crypto. + +It also shows how to add a dependency on Tink using Maven. Please checkout +the pom.xml file. + +Moreoever, since this app shares the same Bazel's WORKSPACE with Tink, its +BUILD file can directly depend on Tink. Note that [a copy of this app] +(https://github.com/thaidn/tink-examples/tree/master/helloworld/java) is +hosted in the tink-examples repo, which uses its own Bazel's WORKSAPCE, +and has to add Tink as a dependency using Bazel's maven_jar rule. + +## Build and run + +**Maven** + +```shell +git clone https://github.com/google/tink +cd tink/examples/helloworld/java +mvn package +echo foo > foo.txt +mvn exec:java -Dexec.args="encrypt --keyset test.cfg --in foo.txt --out bar.encrypted" +mvn exec:java -Dexec.args="decrypt --keyset test.cfg --in bar.encrypted --out foo2.txt" +cat foo2.txt +``` + +**Bazel** + +```shell +git clone https://github.com/google/tink +cd tink +bazel build ... +echo foo > foo.txt +./bazel-bin/examples/helloworld/java/helloworld encrypt --keyset test.cfg --in foo.txt --out bar.encrypted +./bazel-bin/examples/helloworld/java/helloworld decrypt --keyset test.cfg --in bar.encrypted --out foo2.txt +cat foo2.txt +``` diff --git a/examples/helloworld/java/pom.xml b/examples/helloworld/java/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..e5095fbce424b8e3d6accc5a73a1f8d55c06625b --- /dev/null +++ b/examples/helloworld/java/pom.xml @@ -0,0 +1,75 @@ +<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> + + <groupId>com.helloworld</groupId> + <artifactId>helloworld</artifactId> + <version>0.1.0</version> + <packaging>jar</packaging> + + <name>Tink for Java HelloWorld</name> + <url>https://github.com/thaidn/tink-examples/helloworld/java</url> + + <repositories> + <repository> + <id>sonatype-snapshots</id> + <name>sonatype-snapshots</name> + <url>https://oss.sonatype.org/content/repositories/snapshots/</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + </repositories> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + <java.version>1.7</java.version> + </properties> + + <dependencies> + <dependency> + <groupId>args4j</groupId> + <artifactId>args4j</artifactId> + <version>2.33</version> + </dependency> + + <dependency> + <groupId>com.google.crypto.tink</groupId> + <artifactId>tink</artifactId> + <version>1.0.0</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.5.1</version> + <configuration> + <source>${java.version}</source> + <target>${java.version}</target> + <compilerArgument>-Werror</compilerArgument> + <compilerArgument>-Xlint:deprecation</compilerArgument> + </configuration> + </plugin> + + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>exec-maven-plugin</artifactId> + <version>1.2.1</version> + <executions> + <execution> + <goals> + <goal>java</goal> + </goals> + </execution> + </executions> + <configuration> + <mainClass>com.helloworld.HelloWorld</mainClass> + </configuration> + </plugin> + </plugins> + </build> +</project> diff --git a/examples/helloworld/java/src/main/java/com/helloworld/Commands.java b/examples/helloworld/java/src/main/java/com/helloworld/Commands.java new file mode 100644 index 0000000000000000000000000000000000000000..c236c7fbb71496f4786a696a3341a454420ad87a --- /dev/null +++ b/examples/helloworld/java/src/main/java/com/helloworld/Commands.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2017 Google Inc. + * + * 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 com.helloworld; + +import com.google.crypto.tink.Aead; +import com.google.crypto.tink.CleartextKeysetHandle; +import com.google.crypto.tink.JsonKeysetReader; +import com.google.crypto.tink.JsonKeysetWriter; +import com.google.crypto.tink.KeysetHandle; +import com.google.crypto.tink.aead.AeadFactory; +import com.google.crypto.tink.aead.AeadKeyTemplates; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.security.GeneralSecurityException; +import org.kohsuke.args4j.Argument; +import org.kohsuke.args4j.Option; +import org.kohsuke.args4j.spi.SubCommand; +import org.kohsuke.args4j.spi.SubCommandHandler; +import org.kohsuke.args4j.spi.SubCommands; + +/** Defines the different sub-commands and their parameters, for command-line invocation. */ +public final class Commands { + /** An interface for a command-line sub-command. */ + interface Command { + public void run() throws Exception; + } + + static class Options { + @Option( + name = "--keyset", + required = true, + usage = "The path to the keyset, generate new if does not exist" + ) + File keyset; + + @Option(name = "--in", required = true, usage = "The input filename") + File inFile; + + @Option(name = "--out", required = true, usage = "The output filename") + File outFile; + } + + /** Loads a KeysetHandle from {@code keyset} or generate a new one if it doesn't exist. */ + private static KeysetHandle getKeysetHandle(File keyset) + throws GeneralSecurityException, IOException { + if (keyset.exists()) { + // Read the cleartext keyset from disk. + // WARNING: reading cleartext keysets is a bad practice. Tink supports reading/writing + // encrypted keysets, see + // https://github.com/google/tink/blob/master/doc/JAVA-HOWTO.md#loading-existing-keysets. + return CleartextKeysetHandle.read(JsonKeysetReader.withFile(keyset)); + } + KeysetHandle handle = KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM); + CleartextKeysetHandle.write(handle, JsonKeysetWriter.withFile(keyset)); + return handle; + } + + public static class EncryptCommand extends Options implements Command { + @Override + public void run() throws Exception { + // 1. Obtain a keyset handle. + KeysetHandle handle = getKeysetHandle(keyset); + // 2. Get a primitive. + Aead aead = AeadFactory.getPrimitive(handle); + // 3. Do crypto. It's that simple! + byte[] plaintext = Files.readAllBytes(inFile.toPath()); + byte[] ciphertext = aead.encrypt(plaintext, new byte[0] /* additionalData */); + FileOutputStream stream = new FileOutputStream(outFile); + try { + stream.write(ciphertext); + } finally { + stream.close(); + } + } + } + + public static class DecryptCommand extends Options implements Command { + @Override + public void run() throws Exception { + KeysetHandle handle = getKeysetHandle(keyset); + Aead aead = AeadFactory.getPrimitive(handle); + byte[] ciphertext = Files.readAllBytes(inFile.toPath()); + byte[] plaintext = aead.decrypt(ciphertext, new byte[0] /* additionalData */); + FileOutputStream stream = new FileOutputStream(outFile); + try { + stream.write(plaintext); + } finally { + stream.close(); + } + } + } + + @Argument( + metaVar = "command", + required = true, + handler = SubCommandHandler.class, + usage = "The subcommand to run" + ) + @SubCommands({ + @SubCommand(name = "encrypt", impl = EncryptCommand.class), + @SubCommand(name = "decrypt", impl = DecryptCommand.class) + }) + Command command; +} diff --git a/examples/helloworld/java/src/main/java/com/helloworld/HelloWorld.java b/examples/helloworld/java/src/main/java/com/helloworld/HelloWorld.java new file mode 100644 index 0000000000000000000000000000000000000000..b08af45108252ec238382bae61ce4bdac2448e26 --- /dev/null +++ b/examples/helloworld/java/src/main/java/com/helloworld/HelloWorld.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017 Google Inc. + * + * 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 com.helloworld; + +import com.google.crypto.tink.Config; +import com.google.crypto.tink.aead.AeadConfig; +import org.kohsuke.args4j.CmdLineException; +import org.kohsuke.args4j.CmdLineParser; +import java.security.GeneralSecurityException; + +/** + * A command-line tool that can encrypt and decrypt small files with AES128-GCM. + * + * <p>This application uses the <a href="https://github.com/google/tink">Tink<a/> crypto library. + */ +public final class HelloWorld { + public static void main(String[] args) throws Exception { + // Register all AEAD key types with the Tink runtime. + Config.register(AeadConfig.TINK_1_0_0); + + Commands commands = new Commands(); + CmdLineParser parser = new CmdLineParser(commands); + try { + parser.parseArgument(args); + } catch (CmdLineException e) { + System.out.println(e); + e.getParser().printUsage(System.out); + System.exit(1); + } + try { + commands.command.run(); + } catch (GeneralSecurityException e) { + System.out.println("Cannot encrypt or decrypt, got error: " + e.toString()); + System.exit(1); + } + } +} diff --git a/java/BUILD b/java/BUILD index dafc20087dc78db3bbd0334971dd053eaa6aa27d..92a4ec878920977b3662d03fa50d0678a502fcd9 100644 --- a/java/BUILD +++ b/java/BUILD @@ -108,6 +108,7 @@ java_library( java_library( name = "cleartext_keyset_handle", visibility = [ + "//examples:__subpackages__", "//tools/tinkey:__pkg__", ], exports = [