├── .classpath
├── .gitignore
├── .project
├── AndroidManifest.xml
├── LICENSE
├── README.md
├── assets
└── .gitignore
├── libs
└── sc-light-jdk15on-1.47.0.2.jar
├── proguard-project.txt
├── project.properties
├── res
├── drawable-hdpi
│ └── ic_launcher.png
├── drawable-ldpi
│ └── ic_launcher.png
├── drawable-mdpi
│ └── ic_launcher.png
├── drawable-xhdpi
│ └── ic_launcher.png
├── layout
│ └── main.xml
└── values
│ └── strings.xml
└── src
├── android
└── security
│ └── IKeystoreService.java
└── org
└── nick
└── androidkeystore
├── AndroidRsaEngine.java
├── Base64.java
├── Crypto.java
├── KeystoreActivity.java
├── PRNGFixes.java
└── android
└── security
├── KeyStore.java
├── KeyStoreJb43.java
├── KeyStoreKk.java
└── NativeCryptoConstants.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | android-keystore
4 |
5 |
6 |
7 |
8 |
9 | com.android.ide.eclipse.adt.ResourceManagerBuilder
10 |
11 |
12 |
13 |
14 | com.android.ide.eclipse.adt.PreCompilerBuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.jdt.core.javabuilder
20 |
21 |
22 |
23 |
24 | com.android.ide.eclipse.adt.ApkBuilder
25 |
26 |
27 |
28 |
29 |
30 | com.android.ide.eclipse.adt.AndroidNature
31 | org.eclipse.jdt.core.javanature
32 |
33 |
34 |
--------------------------------------------------------------------------------
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2012 Nikolay Elenkov
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Android keystore (credential storage) access
2 | ============================================
3 |
4 | Direct access to Android's credential storage (keystore). Sample code for the
5 | 'Storing application secrets in Android's credential storage' blog post: http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html.
6 |
7 | Accesses the credential storage directly using a private API. Not guaranteed to
8 | work on all Android versions, but tested with 2.1 to 4.0.
9 |
10 | 2013/8/21: updated for Android 4.3. Blog post:
11 | http://nelenkov.blogspot.com/2013/08/credential-storage-enhancements-android-43.html
12 |
13 | 2014/1/16: updated for Android 4.4. Major changes in Android are support for
14 | EC and DSA keys. Added ECDSA sign/verify sample.
15 |
16 |
--------------------------------------------------------------------------------
/assets/.gitignore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/assets/.gitignore
--------------------------------------------------------------------------------
/libs/sc-light-jdk15on-1.47.0.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/libs/sc-light-jdk15on-1.47.0.2.jar
--------------------------------------------------------------------------------
/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}\tools\proguard\proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-19
15 |
--------------------------------------------------------------------------------
/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/res/drawable-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nelenkov/android-keystore/4ac8a68a430334166d3e81701557b4350996dae5/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/layout/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
14 |
15 |
22 |
23 |
30 |
31 |
38 |
39 |
43 |
44 |
50 |
51 |
57 |
58 |
59 |
63 |
64 |
70 |
71 |
77 |
78 |
79 |
83 |
84 |
90 |
91 |
97 |
98 |
99 |
103 |
104 |
110 |
111 |
117 |
118 |
119 |
125 |
126 |
131 |
132 |
139 |
140 |
145 |
146 |
147 |
148 |
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Android Keystore
5 |
6 |
--------------------------------------------------------------------------------
/src/android/security/IKeystoreService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package android.security;
18 |
19 | import android.os.Binder;
20 | import android.os.IBinder;
21 | import android.os.IInterface;
22 | import android.os.Parcel;
23 | import android.os.RemoteException;
24 |
25 | /**
26 | * This must be kept manually in sync with system/security/keystore until AIDL
27 | * can generate both Java and C++ bindings.
28 | *
29 | * @hide
30 | */
31 | public interface IKeystoreService extends IInterface {
32 | public static abstract class Stub extends Binder implements IKeystoreService {
33 | private static class Proxy implements IKeystoreService {
34 | private final IBinder mRemote;
35 |
36 | Proxy(IBinder remote) {
37 | mRemote = remote;
38 | }
39 |
40 | public IBinder asBinder() {
41 | return mRemote;
42 | }
43 |
44 | public String getInterfaceDescriptor() {
45 | return DESCRIPTOR;
46 | }
47 |
48 | public int test() throws RemoteException {
49 | Parcel _data = Parcel.obtain();
50 | Parcel _reply = Parcel.obtain();
51 | int _result;
52 | try {
53 | _data.writeInterfaceToken(DESCRIPTOR);
54 | mRemote.transact(Stub.TRANSACTION_test, _data, _reply, 0);
55 | _reply.readException();
56 | _result = _reply.readInt();
57 | } finally {
58 | _reply.recycle();
59 | _data.recycle();
60 | }
61 | return _result;
62 | }
63 |
64 | public byte[] get(String name) throws RemoteException {
65 | Parcel _data = Parcel.obtain();
66 | Parcel _reply = Parcel.obtain();
67 | byte[] _result;
68 | try {
69 | _data.writeInterfaceToken(DESCRIPTOR);
70 | _data.writeString(name);
71 | mRemote.transact(Stub.TRANSACTION_get, _data, _reply, 0);
72 | _reply.readException();
73 | _result = _reply.createByteArray();
74 | } finally {
75 | _reply.recycle();
76 | _data.recycle();
77 | }
78 | return _result;
79 | }
80 |
81 | public int insert(String name, byte[] item, int uid, int flags) throws RemoteException {
82 | Parcel _data = Parcel.obtain();
83 | Parcel _reply = Parcel.obtain();
84 | int _result;
85 | try {
86 | _data.writeInterfaceToken(DESCRIPTOR);
87 | _data.writeString(name);
88 | _data.writeByteArray(item);
89 | _data.writeInt(uid);
90 | _data.writeInt(flags);
91 | mRemote.transact(Stub.TRANSACTION_insert, _data, _reply, 0);
92 | _reply.readException();
93 | _result = _reply.readInt();
94 | } finally {
95 | _reply.recycle();
96 | _data.recycle();
97 | }
98 | return _result;
99 | }
100 |
101 | public int del(String name, int uid) throws RemoteException {
102 | Parcel _data = Parcel.obtain();
103 | Parcel _reply = Parcel.obtain();
104 | int _result;
105 | try {
106 | _data.writeInterfaceToken(DESCRIPTOR);
107 | _data.writeString(name);
108 | _data.writeInt(uid);
109 | mRemote.transact(Stub.TRANSACTION_del, _data, _reply, 0);
110 | _reply.readException();
111 | _result = _reply.readInt();
112 | } finally {
113 | _reply.recycle();
114 | _data.recycle();
115 | }
116 | return _result;
117 | }
118 |
119 | public int exist(String name, int uid) throws RemoteException {
120 | Parcel _data = Parcel.obtain();
121 | Parcel _reply = Parcel.obtain();
122 | int _result;
123 | try {
124 | _data.writeInterfaceToken(DESCRIPTOR);
125 | _data.writeString(name);
126 | _data.writeInt(uid);
127 | mRemote.transact(Stub.TRANSACTION_exist, _data, _reply, 0);
128 | _reply.readException();
129 | _result = _reply.readInt();
130 | } finally {
131 | _reply.recycle();
132 | _data.recycle();
133 | }
134 | return _result;
135 | }
136 |
137 | public String[] saw(String name, int uid) throws RemoteException {
138 | Parcel _data = Parcel.obtain();
139 | Parcel _reply = Parcel.obtain();
140 | String[] _result;
141 | try {
142 | _data.writeInterfaceToken(DESCRIPTOR);
143 | _data.writeString(name);
144 | _data.writeInt(uid);
145 | mRemote.transact(Stub.TRANSACTION_saw, _data, _reply, 0);
146 | _reply.readException();
147 | int size = _reply.readInt();
148 | _result = new String[size];
149 | for (int i = 0; i < size; i++) {
150 | _result[i] = _reply.readString();
151 | }
152 | int _ret = _reply.readInt();
153 | if (_ret != 1) {
154 | return null;
155 | }
156 | } finally {
157 | _reply.recycle();
158 | _data.recycle();
159 | }
160 | return _result;
161 | }
162 |
163 | @Override
164 | public int reset() throws RemoteException {
165 | Parcel _data = Parcel.obtain();
166 | Parcel _reply = Parcel.obtain();
167 | int _result;
168 | try {
169 | _data.writeInterfaceToken(DESCRIPTOR);
170 | mRemote.transact(Stub.TRANSACTION_reset, _data, _reply, 0);
171 | _reply.readException();
172 | _result = _reply.readInt();
173 | } finally {
174 | _reply.recycle();
175 | _data.recycle();
176 | }
177 | return _result;
178 | }
179 |
180 | public int password(String password) throws RemoteException {
181 | Parcel _data = Parcel.obtain();
182 | Parcel _reply = Parcel.obtain();
183 | int _result;
184 | try {
185 | _data.writeInterfaceToken(DESCRIPTOR);
186 | _data.writeString(password);
187 | mRemote.transact(Stub.TRANSACTION_password, _data, _reply, 0);
188 | _reply.readException();
189 | _result = _reply.readInt();
190 | } finally {
191 | _reply.recycle();
192 | _data.recycle();
193 | }
194 | return _result;
195 | }
196 |
197 | public int lock() throws RemoteException {
198 | Parcel _data = Parcel.obtain();
199 | Parcel _reply = Parcel.obtain();
200 | int _result;
201 | try {
202 | _data.writeInterfaceToken(DESCRIPTOR);
203 | mRemote.transact(Stub.TRANSACTION_lock, _data, _reply, 0);
204 | _reply.readException();
205 | _result = _reply.readInt();
206 | } finally {
207 | _reply.recycle();
208 | _data.recycle();
209 | }
210 | return _result;
211 | }
212 |
213 | public int unlock(String password) throws RemoteException {
214 | Parcel _data = Parcel.obtain();
215 | Parcel _reply = Parcel.obtain();
216 | int _result;
217 | try {
218 | _data.writeInterfaceToken(DESCRIPTOR);
219 | _data.writeString(password);
220 | mRemote.transact(Stub.TRANSACTION_unlock, _data, _reply, 0);
221 | _reply.readException();
222 | _result = _reply.readInt();
223 | } finally {
224 | _reply.recycle();
225 | _data.recycle();
226 | }
227 | return _result;
228 | }
229 |
230 | @Override
231 | public int zero() throws RemoteException {
232 | Parcel _data = Parcel.obtain();
233 | Parcel _reply = Parcel.obtain();
234 | int _result;
235 | try {
236 | _data.writeInterfaceToken(DESCRIPTOR);
237 | mRemote.transact(Stub.TRANSACTION_zero, _data, _reply, 0);
238 | _reply.readException();
239 | _result = _reply.readInt();
240 | } finally {
241 | _reply.recycle();
242 | _data.recycle();
243 | }
244 | return _result;
245 | }
246 |
247 | // 4.3 version
248 | public int generate(String name, int uid, int flags) throws RemoteException {
249 | Parcel _data = Parcel.obtain();
250 | Parcel _reply = Parcel.obtain();
251 | int _result;
252 | try {
253 | _data.writeInterfaceToken(DESCRIPTOR);
254 | _data.writeString(name);
255 | _data.writeInt(uid);
256 | _data.writeInt(flags);
257 | mRemote.transact(Stub.TRANSACTION_generate, _data, _reply, 0);
258 | _reply.readException();
259 | _result = _reply.readInt();
260 | } finally {
261 | _reply.recycle();
262 | _data.recycle();
263 | }
264 | return _result;
265 | }
266 |
267 | public int generate(String name, int uid, int keyType, int keySize, int flags,
268 | byte[][] args) throws RemoteException {
269 | Parcel _data = Parcel.obtain();
270 | Parcel _reply = Parcel.obtain();
271 | int _result;
272 | try {
273 | _data.writeInterfaceToken(DESCRIPTOR);
274 | _data.writeString(name);
275 | _data.writeInt(uid);
276 | _data.writeInt(keyType);
277 | _data.writeInt(keySize);
278 | _data.writeInt(flags);
279 | if (args == null) {
280 | _data.writeInt(0);
281 | } else {
282 | _data.writeInt(args.length);
283 | for (int i = 0; i < args.length; i++) {
284 | _data.writeByteArray(args[i]);
285 | }
286 | }
287 | mRemote.transact(Stub.TRANSACTION_generate, _data, _reply, 0);
288 | _reply.readException();
289 | _result = _reply.readInt();
290 | } finally {
291 | _reply.recycle();
292 | _data.recycle();
293 | }
294 | return _result;
295 | }
296 |
297 | public int import_key(String name, byte[] data, int uid, int flags)
298 | throws RemoteException {
299 | Parcel _data = Parcel.obtain();
300 | Parcel _reply = Parcel.obtain();
301 | int _result;
302 | try {
303 | _data.writeInterfaceToken(DESCRIPTOR);
304 | _data.writeString(name);
305 | _data.writeByteArray(data);
306 | _data.writeInt(uid);
307 | _data.writeInt(flags);
308 | mRemote.transact(Stub.TRANSACTION_import, _data, _reply, 0);
309 | _reply.readException();
310 | _result = _reply.readInt();
311 | } finally {
312 | _reply.recycle();
313 | _data.recycle();
314 | }
315 | return _result;
316 | }
317 |
318 | public byte[] sign(String name, byte[] data) throws RemoteException {
319 | Parcel _data = Parcel.obtain();
320 | Parcel _reply = Parcel.obtain();
321 | byte[] _result;
322 | try {
323 | _data.writeInterfaceToken(DESCRIPTOR);
324 | _data.writeString(name);
325 | _data.writeByteArray(data);
326 | mRemote.transact(Stub.TRANSACTION_sign, _data, _reply, 0);
327 | _reply.readException();
328 | _result = _reply.createByteArray();
329 | } finally {
330 | _reply.recycle();
331 | _data.recycle();
332 | }
333 | return _result;
334 | }
335 |
336 | public int verify(String name, byte[] data, byte[] signature) throws RemoteException {
337 | Parcel _data = Parcel.obtain();
338 | Parcel _reply = Parcel.obtain();
339 | int _result;
340 | try {
341 | _data.writeInterfaceToken(DESCRIPTOR);
342 | _data.writeString(name);
343 | _data.writeByteArray(data);
344 | _data.writeByteArray(signature);
345 | mRemote.transact(Stub.TRANSACTION_verify, _data, _reply, 0);
346 | _reply.readException();
347 | _result = _reply.readInt();
348 | } finally {
349 | _reply.recycle();
350 | _data.recycle();
351 | }
352 | return _result;
353 | }
354 |
355 | public byte[] get_pubkey(String name) throws RemoteException {
356 | Parcel _data = Parcel.obtain();
357 | Parcel _reply = Parcel.obtain();
358 | byte[] _result;
359 | try {
360 | _data.writeInterfaceToken(DESCRIPTOR);
361 | _data.writeString(name);
362 | mRemote.transact(Stub.TRANSACTION_get_pubkey, _data, _reply, 0);
363 | _reply.readException();
364 | _result = _reply.createByteArray();
365 | } finally {
366 | _reply.recycle();
367 | _data.recycle();
368 | }
369 | return _result;
370 | }
371 |
372 | public int del_key(String name, int uid) throws RemoteException {
373 | Parcel _data = Parcel.obtain();
374 | Parcel _reply = Parcel.obtain();
375 | int _result;
376 | try {
377 | _data.writeInterfaceToken(DESCRIPTOR);
378 | _data.writeString(name);
379 | _data.writeInt(uid);
380 | mRemote.transact(Stub.TRANSACTION_del_key, _data, _reply, 0);
381 | _reply.readException();
382 | _result = _reply.readInt();
383 | } finally {
384 | _reply.recycle();
385 | _data.recycle();
386 | }
387 | return _result;
388 | }
389 |
390 | public int grant(String name, int granteeUid) throws RemoteException {
391 | Parcel _data = Parcel.obtain();
392 | Parcel _reply = Parcel.obtain();
393 | int _result;
394 | try {
395 | _data.writeInterfaceToken(DESCRIPTOR);
396 | _data.writeString(name);
397 | _data.writeInt(granteeUid);
398 | mRemote.transact(Stub.TRANSACTION_grant, _data, _reply, 0);
399 | _reply.readException();
400 | _result = _reply.readInt();
401 | } finally {
402 | _reply.recycle();
403 | _data.recycle();
404 | }
405 | return _result;
406 | }
407 |
408 | public int ungrant(String name, int granteeUid) throws RemoteException {
409 | Parcel _data = Parcel.obtain();
410 | Parcel _reply = Parcel.obtain();
411 | int _result;
412 | try {
413 | _data.writeInterfaceToken(DESCRIPTOR);
414 | _data.writeString(name);
415 | _data.writeInt(granteeUid);
416 | mRemote.transact(Stub.TRANSACTION_ungrant, _data, _reply, 0);
417 | _reply.readException();
418 | _result = _reply.readInt();
419 | } finally {
420 | _reply.recycle();
421 | _data.recycle();
422 | }
423 | return _result;
424 | }
425 |
426 | @Override
427 | public long getmtime(String name) throws RemoteException {
428 | Parcel _data = Parcel.obtain();
429 | Parcel _reply = Parcel.obtain();
430 | long _result;
431 | try {
432 | _data.writeInterfaceToken(DESCRIPTOR);
433 | _data.writeString(name);
434 | mRemote.transact(Stub.TRANSACTION_getmtime, _data, _reply, 0);
435 | _reply.readException();
436 | _result = _reply.readLong();
437 | } finally {
438 | _reply.recycle();
439 | _data.recycle();
440 | }
441 | return _result;
442 | }
443 |
444 | @Override
445 | public int duplicate(String srcKey, int srcUid, String destKey, int destUid)
446 | throws RemoteException {
447 | Parcel _data = Parcel.obtain();
448 | Parcel _reply = Parcel.obtain();
449 | int _result;
450 | try {
451 | _data.writeInterfaceToken(DESCRIPTOR);
452 | _data.writeString(srcKey);
453 | _data.writeInt(srcUid);
454 | _data.writeString(destKey);
455 | _data.writeInt(destUid);
456 | mRemote.transact(Stub.TRANSACTION_duplicate, _data, _reply, 0);
457 | _reply.readException();
458 | _result = _reply.readInt();
459 | } finally {
460 | _reply.recycle();
461 | _data.recycle();
462 | }
463 | return _result;
464 | }
465 |
466 | // 4.3 version
467 | @Override
468 | public int is_hardware_backed() throws RemoteException {
469 | Parcel _data = Parcel.obtain();
470 | Parcel _reply = Parcel.obtain();
471 | int _result;
472 | try {
473 | _data.writeInterfaceToken(DESCRIPTOR);
474 | mRemote.transact(Stub.TRANSACTION_is_hardware_backed, _data, _reply, 0);
475 | _reply.readException();
476 | _result = _reply.readInt();
477 | } finally {
478 | _reply.recycle();
479 | _data.recycle();
480 | }
481 | return _result;
482 | }
483 |
484 | @Override
485 | public int is_hardware_backed(String keyType) throws RemoteException {
486 | Parcel _data = Parcel.obtain();
487 | Parcel _reply = Parcel.obtain();
488 | int _result;
489 | try {
490 | _data.writeInterfaceToken(DESCRIPTOR);
491 | _data.writeString(keyType);
492 | mRemote.transact(Stub.TRANSACTION_is_hardware_backed, _data, _reply, 0);
493 | _reply.readException();
494 | _result = _reply.readInt();
495 | } finally {
496 | _reply.recycle();
497 | _data.recycle();
498 | }
499 | return _result;
500 | }
501 |
502 | @Override
503 | public int clear_uid(long uid) throws RemoteException {
504 | Parcel _data = Parcel.obtain();
505 | Parcel _reply = Parcel.obtain();
506 | int _result;
507 | try {
508 | _data.writeInterfaceToken(DESCRIPTOR);
509 | _data.writeLong(uid);
510 | mRemote.transact(Stub.TRANSACTION_clear_uid, _data, _reply, 0);
511 | _reply.readException();
512 | _result = _reply.readInt();
513 | } finally {
514 | _reply.recycle();
515 | _data.recycle();
516 | }
517 | return _result;
518 | }
519 | }
520 |
521 | private static final String DESCRIPTOR = "android.security.keystore";
522 |
523 | static final int TRANSACTION_test = IBinder.FIRST_CALL_TRANSACTION + 0;
524 | static final int TRANSACTION_get = IBinder.FIRST_CALL_TRANSACTION + 1;
525 | static final int TRANSACTION_insert = IBinder.FIRST_CALL_TRANSACTION + 2;
526 | static final int TRANSACTION_del = IBinder.FIRST_CALL_TRANSACTION + 3;
527 | static final int TRANSACTION_exist = IBinder.FIRST_CALL_TRANSACTION + 4;
528 | static final int TRANSACTION_saw = IBinder.FIRST_CALL_TRANSACTION + 5;
529 | static final int TRANSACTION_reset = IBinder.FIRST_CALL_TRANSACTION + 6;
530 | static final int TRANSACTION_password = IBinder.FIRST_CALL_TRANSACTION + 7;
531 | static final int TRANSACTION_lock = IBinder.FIRST_CALL_TRANSACTION + 8;
532 | static final int TRANSACTION_unlock = IBinder.FIRST_CALL_TRANSACTION + 9;
533 | static final int TRANSACTION_zero = IBinder.FIRST_CALL_TRANSACTION + 10;
534 | static final int TRANSACTION_generate = IBinder.FIRST_CALL_TRANSACTION + 11;
535 | static final int TRANSACTION_import = IBinder.FIRST_CALL_TRANSACTION + 12;
536 | static final int TRANSACTION_sign = IBinder.FIRST_CALL_TRANSACTION + 13;
537 | static final int TRANSACTION_verify = IBinder.FIRST_CALL_TRANSACTION + 14;
538 | static final int TRANSACTION_get_pubkey = IBinder.FIRST_CALL_TRANSACTION + 15;
539 | static final int TRANSACTION_del_key = IBinder.FIRST_CALL_TRANSACTION + 16;
540 | static final int TRANSACTION_grant = IBinder.FIRST_CALL_TRANSACTION + 17;
541 | static final int TRANSACTION_ungrant = IBinder.FIRST_CALL_TRANSACTION + 18;
542 | static final int TRANSACTION_getmtime = IBinder.FIRST_CALL_TRANSACTION + 19;
543 | static final int TRANSACTION_duplicate = IBinder.FIRST_CALL_TRANSACTION + 20;
544 | static final int TRANSACTION_is_hardware_backed = IBinder.FIRST_CALL_TRANSACTION + 21;
545 | static final int TRANSACTION_clear_uid = IBinder.FIRST_CALL_TRANSACTION + 22;
546 |
547 | /**
548 | * Cast an IBinder object into an IKeystoreService interface, generating
549 | * a proxy if needed.
550 | */
551 | public static IKeystoreService asInterface(IBinder obj) {
552 | if (obj == null) {
553 | return null;
554 | }
555 | IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
556 | if (iin != null && iin instanceof IKeystoreService) {
557 | return (IKeystoreService) iin;
558 | }
559 | return new IKeystoreService.Stub.Proxy(obj);
560 | }
561 |
562 | /** Construct the stub at attach it to the interface. */
563 | public Stub() {
564 | attachInterface(this, DESCRIPTOR);
565 | }
566 |
567 | public IBinder asBinder() {
568 | return this;
569 | }
570 |
571 | @Override
572 | public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
573 | throws RemoteException {
574 | switch (code) {
575 | case INTERFACE_TRANSACTION: {
576 | reply.writeString(DESCRIPTOR);
577 | return true;
578 | }
579 | case TRANSACTION_test: {
580 | data.enforceInterface(DESCRIPTOR);
581 | int resultCode = test();
582 | reply.writeNoException();
583 | reply.writeInt(resultCode);
584 | return true;
585 | }
586 | }
587 | return super.onTransact(code, data, reply, flags);
588 | }
589 | }
590 |
591 | public int test() throws RemoteException;
592 |
593 | public byte[] get(String name) throws RemoteException;
594 |
595 | public int insert(String name, byte[] item, int uid, int flags) throws RemoteException;
596 |
597 | public int del(String name, int uid) throws RemoteException;
598 |
599 | public int exist(String name, int uid) throws RemoteException;
600 |
601 | public String[] saw(String name, int uid) throws RemoteException;
602 |
603 | public int reset() throws RemoteException;
604 |
605 | public int password(String password) throws RemoteException;
606 |
607 | public int lock() throws RemoteException;
608 |
609 | public int unlock(String password) throws RemoteException;
610 |
611 | public int zero() throws RemoteException;
612 |
613 | public int generate(String name, int uid, int flags) throws RemoteException;
614 |
615 | public int generate(String name, int uid, int keyType, int keySize, int flags, byte[][] args)
616 | throws RemoteException;
617 |
618 | public int import_key(String name, byte[] data, int uid, int flags) throws RemoteException;
619 |
620 | public byte[] sign(String name, byte[] data) throws RemoteException;
621 |
622 | public int verify(String name, byte[] data, byte[] signature) throws RemoteException;
623 |
624 | public byte[] get_pubkey(String name) throws RemoteException;
625 |
626 | public int del_key(String name, int uid) throws RemoteException;
627 |
628 | public int grant(String name, int granteeUid) throws RemoteException;
629 |
630 | public int ungrant(String name, int granteeUid) throws RemoteException;
631 |
632 | public long getmtime(String name) throws RemoteException;
633 |
634 | public int duplicate(String srcKey, int srcUid, String destKey, int destUid)
635 | throws RemoteException;
636 |
637 | public int is_hardware_backed() throws RemoteException;
638 |
639 | public int is_hardware_backed(String string) throws RemoteException;
640 |
641 | public int clear_uid(long uid) throws RemoteException;
642 | }
643 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/AndroidRsaEngine.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore;
2 |
3 | import java.io.IOException;
4 | import java.security.InvalidKeyException;
5 | import java.security.KeyStore;
6 | import java.security.KeyStoreException;
7 | import java.security.NoSuchAlgorithmException;
8 | import java.security.UnrecoverableEntryException;
9 | import java.security.cert.CertificateException;
10 | import java.security.interfaces.RSAPrivateKey;
11 | import java.security.interfaces.RSAPublicKey;
12 |
13 | import javax.crypto.BadPaddingException;
14 | import javax.crypto.Cipher;
15 | import javax.crypto.IllegalBlockSizeException;
16 | import javax.crypto.NoSuchPaddingException;
17 |
18 | import org.spongycastle.crypto.AsymmetricBlockCipher;
19 | import org.spongycastle.crypto.CipherParameters;
20 | import org.spongycastle.crypto.InvalidCipherTextException;
21 |
22 | import android.util.Log;
23 |
24 | public class AndroidRsaEngine implements AsymmetricBlockCipher {
25 |
26 | private static final String TAG = AndroidRsaEngine.class.getSimpleName();
27 | private static final boolean DEBUG = false;
28 |
29 | private String keyAlias;
30 | private boolean isSigner;
31 |
32 | private Cipher cipher;
33 | private KeyStore keyStore;
34 | private RSAPrivateKey privateKey;
35 | private RSAPublicKey publicKey;
36 |
37 | private boolean forEncryption;
38 | private CipherParameters params;
39 |
40 | public AndroidRsaEngine(String keyAlias, boolean isSigner) {
41 | this.keyAlias = keyAlias;
42 | this.isSigner = isSigner;
43 | try {
44 | this.cipher = Cipher.getInstance("RSA/ECB/NoPadding");
45 | this.keyStore = KeyStore.getInstance("AndroidKeyStore");
46 | keyStore.load(null);
47 | java.security.KeyStore.Entry keyEntry = keyStore.getEntry(
48 | this.keyAlias, null);
49 | publicKey = (RSAPublicKey) ((java.security.KeyStore.PrivateKeyEntry) keyEntry)
50 | .getCertificate().getPublicKey();
51 | privateKey = (RSAPrivateKey) ((java.security.KeyStore.PrivateKeyEntry) keyEntry)
52 | .getPrivateKey();
53 | } catch (NoSuchAlgorithmException e) {
54 | throw new RuntimeException(e);
55 | } catch (NoSuchPaddingException e) {
56 | throw new RuntimeException(e);
57 | } catch (KeyStoreException e) {
58 | throw new RuntimeException(e);
59 | } catch (CertificateException e) {
60 | throw new RuntimeException(e);
61 | } catch (IOException e) {
62 | throw new RuntimeException(e);
63 | } catch (UnrecoverableEntryException e) {
64 | throw new RuntimeException(e);
65 | }
66 | }
67 |
68 | @Override
69 | public int getInputBlockSize() {
70 | int bitSize = publicKey.getModulus().bitLength();
71 |
72 | if (forEncryption) {
73 | return (bitSize + 7) / 8 - 1;
74 | } else {
75 | return (bitSize + 7) / 8;
76 | }
77 | }
78 |
79 | @Override
80 | public int getOutputBlockSize() {
81 | int bitSize = publicKey.getModulus().bitLength();
82 |
83 | if (forEncryption) {
84 | return (bitSize + 7) / 8;
85 | } else {
86 | return (bitSize + 7) / 8 - 1;
87 | }
88 | }
89 |
90 | @Override
91 | public void init(boolean forEncryption, CipherParameters param) {
92 | this.forEncryption = forEncryption;
93 | if (DEBUG) {
94 | Log.d(TAG, "forEncryption: " + forEncryption);
95 | }
96 | this.params = param;
97 | if (DEBUG) {
98 | Log.d(TAG, "CipherParameters: " + param);
99 | }
100 |
101 | try {
102 | if (forEncryption) {
103 | cipher.init(Cipher.ENCRYPT_MODE, isSigner ? privateKey
104 | : publicKey);
105 | } else {
106 | cipher.init(Cipher.DECRYPT_MODE, isSigner ? publicKey
107 | : privateKey);
108 | }
109 | } catch (InvalidKeyException e) {
110 | throw new RuntimeException(e);
111 | }
112 | }
113 |
114 | @Override
115 | public byte[] processBlock(byte[] in, int inOff, int inLen)
116 | throws InvalidCipherTextException {
117 | try {
118 | String inputStr = Crypto.toHex(in);
119 | if (DEBUG) {
120 | Log.d(TAG, "processBlock() INPUT: " + inputStr);
121 | }
122 | byte[] result = cipher.doFinal(in, inOff, inLen);
123 | String outputStr = Crypto.toHex(result);
124 | if (DEBUG) {
125 | Log.d(TAG, "processBlock() OUTPUT: " + outputStr);
126 | }
127 | byte[] converted = convertOutput(result);
128 | String convertedStr = Crypto.toHex(converted);
129 | if (DEBUG) {
130 | Log.d(TAG, "processBlock() CONVERTED: " + convertedStr);
131 | }
132 |
133 | return converted;
134 | } catch (IllegalBlockSizeException e) {
135 | throw new InvalidCipherTextException("Illegal block size: "
136 | + e.getMessage());
137 | } catch (BadPaddingException e) {
138 | throw new InvalidCipherTextException("Bad padding: "
139 | + e.getMessage());
140 | }
141 | }
142 |
143 | // from BC's RSACoreEngine
144 | public byte[] convertOutput(byte[] output) {
145 | if (forEncryption) {
146 | if (output[0] == 0 && output.length > getOutputBlockSize()) // have ended up with an extra zero byte, copy down.
147 | {
148 | byte[] tmp = new byte[output.length - 1];
149 |
150 | System.arraycopy(output, 1, tmp, 0, tmp.length);
151 |
152 | return tmp;
153 | }
154 |
155 | if (output.length < getOutputBlockSize()) // have ended up with less bytes than normal, lengthen
156 | {
157 | byte[] tmp = new byte[getOutputBlockSize()];
158 |
159 | System.arraycopy(output, 0, tmp, tmp.length - output.length,
160 | output.length);
161 |
162 | return tmp;
163 | }
164 | } else {
165 | if (output[0] == 0) // have ended up with an extra zero byte, copy down.
166 | {
167 | byte[] tmp = new byte[output.length - 1];
168 |
169 | System.arraycopy(output, 1, tmp, 0, tmp.length);
170 |
171 | return tmp;
172 | }
173 | }
174 |
175 | return output;
176 | }
177 |
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/Base64.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2010 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | //package android.util;
18 | package org.nick.androidkeystore;
19 |
20 | import java.io.UnsupportedEncodingException;
21 |
22 | import android.util.Base64OutputStream;
23 |
24 | /**
25 | * Utilities for encoding and decoding the Base64 representation of
26 | * binary data. See RFCs 2045 and 3548.
29 | */
30 | public class Base64 {
31 | /**
32 | * Default values for encoder/decoder flags.
33 | */
34 | public static final int DEFAULT = 0;
35 |
36 | /**
37 | * Encoder flag bit to omit the padding '=' characters at the end
38 | * of the output (if any).
39 | */
40 | public static final int NO_PADDING = 1;
41 |
42 | /**
43 | * Encoder flag bit to omit all line terminators (i.e., the output
44 | * will be on one long line).
45 | */
46 | public static final int NO_WRAP = 2;
47 |
48 | /**
49 | * Encoder flag bit to indicate lines should be terminated with a
50 | * CRLF pair instead of just an LF. Has no effect if {@code
51 | * NO_WRAP} is specified as well.
52 | */
53 | public static final int CRLF = 4;
54 |
55 | /**
56 | * Encoder/decoder flag bit to indicate using the "URL and
57 | * filename safe" variant of Base64 (see RFC 3548 section 4) where
58 | * {@code -} and {@code _} are used in place of {@code +} and
59 | * {@code /}.
60 | */
61 | public static final int URL_SAFE = 8;
62 |
63 | /**
64 | * Flag to pass to {@link Base64OutputStream} to indicate that it
65 | * should not close the output stream it is wrapping when it
66 | * itself is closed.
67 | */
68 | public static final int NO_CLOSE = 16;
69 |
70 | // --------------------------------------------------------
71 | // shared code
72 | // --------------------------------------------------------
73 |
74 | /* package */static abstract class Coder {
75 | public byte[] output;
76 | public int op;
77 |
78 | /**
79 | * Encode/decode another block of input data. this.output is
80 | * provided by the caller, and must be big enough to hold all
81 | * the coded data. On exit, this.opwill be set to the length
82 | * of the coded data.
83 | *
84 | * @param finish true if this is the final call to process for
85 | * this object. Will finalize the coder state and
86 | * include any final bytes in the output.
87 | *
88 | * @return true if the input so far is good; false if some
89 | * error has been detected in the input stream..
90 | */
91 | public abstract boolean process(byte[] input, int offset, int len,
92 | boolean finish);
93 |
94 | /**
95 | * @return the maximum number of bytes a call to process()
96 | * could produce for the given number of input bytes. This may
97 | * be an overestimate.
98 | */
99 | public abstract int maxOutputSize(int len);
100 | }
101 |
102 | // --------------------------------------------------------
103 | // decoding
104 | // --------------------------------------------------------
105 |
106 | /**
107 | * Decode the Base64-encoded data in input and return the data in
108 | * a new byte array.
109 | *
110 | *
The padding '=' characters at the end are considered optional, but
111 | * if any are present, there must be the correct number of them.
112 | *
113 | * @param str the input String to decode, which is converted to
114 | * bytes using the default charset
115 | * @param flags controls certain features of the decoded output.
116 | * Pass {@code DEFAULT} to decode standard Base64.
117 | *
118 | * @throws IllegalArgumentException if the input contains
119 | * incorrect padding
120 | */
121 | public static byte[] decode(String str, int flags) {
122 | return decode(str.getBytes(), flags);
123 | }
124 |
125 | /**
126 | * Decode the Base64-encoded data in input and return the data in
127 | * a new byte array.
128 | *
129 | *
The padding '=' characters at the end are considered optional, but
130 | * if any are present, there must be the correct number of them.
131 | *
132 | * @param input the input array to decode
133 | * @param flags controls certain features of the decoded output.
134 | * Pass {@code DEFAULT} to decode standard Base64.
135 | *
136 | * @throws IllegalArgumentException if the input contains
137 | * incorrect padding
138 | */
139 | public static byte[] decode(byte[] input, int flags) {
140 | return decode(input, 0, input.length, flags);
141 | }
142 |
143 | /**
144 | * Decode the Base64-encoded data in input and return the data in
145 | * a new byte array.
146 | *
147 | *
The padding '=' characters at the end are considered optional, but
148 | * if any are present, there must be the correct number of them.
149 | *
150 | * @param input the data to decode
151 | * @param offset the position within the input array at which to start
152 | * @param len the number of bytes of input to decode
153 | * @param flags controls certain features of the decoded output.
154 | * Pass {@code DEFAULT} to decode standard Base64.
155 | *
156 | * @throws IllegalArgumentException if the input contains
157 | * incorrect padding
158 | */
159 | public static byte[] decode(byte[] input, int offset, int len, int flags) {
160 | // Allocate space for the most data the input could represent.
161 | // (It could contain less if it contains whitespace, etc.)
162 | Decoder decoder = new Decoder(flags, new byte[len * 3 / 4]);
163 |
164 | if (!decoder.process(input, offset, len, true)) {
165 | throw new IllegalArgumentException("bad base-64");
166 | }
167 |
168 | // Maybe we got lucky and allocated exactly enough output space.
169 | if (decoder.op == decoder.output.length) {
170 | return decoder.output;
171 | }
172 |
173 | // Need to shorten the array, so allocate a new one of the
174 | // right size and copy.
175 | byte[] temp = new byte[decoder.op];
176 | System.arraycopy(decoder.output, 0, temp, 0, decoder.op);
177 | return temp;
178 | }
179 |
180 | /* package */static class Decoder extends Coder {
181 | /**
182 | * Lookup table for turning bytes into their position in the
183 | * Base64 alphabet.
184 | */
185 | private static final int DECODE[] = { -1, -1, -1, -1, -1, -1, -1, -1,
186 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
187 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
188 | -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
189 | 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
190 | 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
191 | 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34,
192 | 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
193 | 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
194 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
195 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
196 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
197 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
198 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
199 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
200 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
201 | -1, -1, -1, -1, -1, -1, };
202 |
203 | /**
204 | * Decode lookup table for the "web safe" variant (RFC 3548
205 | * sec. 4) where - and _ replace + and /.
206 | */
207 | private static final int DECODE_WEBSAFE[] = { -1, -1, -1, -1, -1, -1,
208 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
209 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
210 | -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, 52, 53, 54, 55, 56, 57,
211 | 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5,
212 | 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
213 | 23, 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32,
214 | 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
215 | 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
216 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
217 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
218 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
219 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
220 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
221 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
222 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
223 | -1, -1, -1, -1, -1, -1, -1, -1, };
224 |
225 | /** Non-data values in the DECODE arrays. */
226 | private static final int SKIP = -1;
227 | private static final int EQUALS = -2;
228 |
229 | /**
230 | * States 0-3 are reading through the next input tuple.
231 | * State 4 is having read one '=' and expecting exactly
232 | * one more.
233 | * State 5 is expecting no more data or padding characters
234 | * in the input.
235 | * State 6 is the error state; an error has been detected
236 | * in the input and no future input can "fix" it.
237 | */
238 | private int state; // state number (0 to 6)
239 | private int value;
240 |
241 | final private int[] alphabet;
242 |
243 | public Decoder(int flags, byte[] output) {
244 | this.output = output;
245 |
246 | alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE;
247 | state = 0;
248 | value = 0;
249 | }
250 |
251 | /**
252 | * @return an overestimate for the number of bytes {@code
253 | * len} bytes could decode to.
254 | */
255 | public int maxOutputSize(int len) {
256 | return len * 3 / 4 + 10;
257 | }
258 |
259 | /**
260 | * Decode another block of input data.
261 | *
262 | * @return true if the state machine is still healthy. false if
263 | * bad base-64 data has been detected in the input stream.
264 | */
265 | public boolean process(byte[] input, int offset, int len, boolean finish) {
266 | if (this.state == 6)
267 | return false;
268 |
269 | int p = offset;
270 | len += offset;
271 |
272 | // Using local variables makes the decoder about 12%
273 | // faster than if we manipulate the member variables in
274 | // the loop. (Even alphabet makes a measurable
275 | // difference, which is somewhat surprising to me since
276 | // the member variable is final.)
277 | int state = this.state;
278 | int value = this.value;
279 | int op = 0;
280 | final byte[] output = this.output;
281 | final int[] alphabet = this.alphabet;
282 |
283 | while (p < len) {
284 | // Try the fast path: we're starting a new tuple and the
285 | // next four bytes of the input stream are all data
286 | // bytes. This corresponds to going through states
287 | // 0-1-2-3-0. We expect to use this method for most of
288 | // the data.
289 | //
290 | // If any of the next four bytes of input are non-data
291 | // (whitespace, etc.), value will end up negative. (All
292 | // the non-data values in decode are small negative
293 | // numbers, so shifting any of them up and or'ing them
294 | // together will result in a value with its top bit set.)
295 | //
296 | // You can remove this whole block and the output should
297 | // be the same, just slower.
298 | if (state == 0) {
299 | while (p + 4 <= len
300 | && (value = ((alphabet[input[p] & 0xff] << 18)
301 | | (alphabet[input[p + 1] & 0xff] << 12)
302 | | (alphabet[input[p + 2] & 0xff] << 6) | (alphabet[input[p + 3] & 0xff]))) >= 0) {
303 | output[op + 2] = (byte) value;
304 | output[op + 1] = (byte) (value >> 8);
305 | output[op] = (byte) (value >> 16);
306 | op += 3;
307 | p += 4;
308 | }
309 | if (p >= len)
310 | break;
311 | }
312 |
313 | // The fast path isn't available -- either we've read a
314 | // partial tuple, or the next four input bytes aren't all
315 | // data, or whatever. Fall back to the slower state
316 | // machine implementation.
317 |
318 | int d = alphabet[input[p++] & 0xff];
319 |
320 | switch (state) {
321 | case 0:
322 | if (d >= 0) {
323 | value = d;
324 | ++state;
325 | } else if (d != SKIP) {
326 | this.state = 6;
327 | return false;
328 | }
329 | break;
330 |
331 | case 1:
332 | if (d >= 0) {
333 | value = (value << 6) | d;
334 | ++state;
335 | } else if (d != SKIP) {
336 | this.state = 6;
337 | return false;
338 | }
339 | break;
340 |
341 | case 2:
342 | if (d >= 0) {
343 | value = (value << 6) | d;
344 | ++state;
345 | } else if (d == EQUALS) {
346 | // Emit the last (partial) output tuple;
347 | // expect exactly one more padding character.
348 | output[op++] = (byte) (value >> 4);
349 | state = 4;
350 | } else if (d != SKIP) {
351 | this.state = 6;
352 | return false;
353 | }
354 | break;
355 |
356 | case 3:
357 | if (d >= 0) {
358 | // Emit the output triple and return to state 0.
359 | value = (value << 6) | d;
360 | output[op + 2] = (byte) value;
361 | output[op + 1] = (byte) (value >> 8);
362 | output[op] = (byte) (value >> 16);
363 | op += 3;
364 | state = 0;
365 | } else if (d == EQUALS) {
366 | // Emit the last (partial) output tuple;
367 | // expect no further data or padding characters.
368 | output[op + 1] = (byte) (value >> 2);
369 | output[op] = (byte) (value >> 10);
370 | op += 2;
371 | state = 5;
372 | } else if (d != SKIP) {
373 | this.state = 6;
374 | return false;
375 | }
376 | break;
377 |
378 | case 4:
379 | if (d == EQUALS) {
380 | ++state;
381 | } else if (d != SKIP) {
382 | this.state = 6;
383 | return false;
384 | }
385 | break;
386 |
387 | case 5:
388 | if (d != SKIP) {
389 | this.state = 6;
390 | return false;
391 | }
392 | break;
393 | }
394 | }
395 |
396 | if (!finish) {
397 | // We're out of input, but a future call could provide
398 | // more.
399 | this.state = state;
400 | this.value = value;
401 | this.op = op;
402 | return true;
403 | }
404 |
405 | // Done reading input. Now figure out where we are left in
406 | // the state machine and finish up.
407 |
408 | switch (state) {
409 | case 0:
410 | // Output length is a multiple of three. Fine.
411 | break;
412 | case 1:
413 | // Read one extra input byte, which isn't enough to
414 | // make another output byte. Illegal.
415 | this.state = 6;
416 | return false;
417 | case 2:
418 | // Read two extra input bytes, enough to emit 1 more
419 | // output byte. Fine.
420 | output[op++] = (byte) (value >> 4);
421 | break;
422 | case 3:
423 | // Read three extra input bytes, enough to emit 2 more
424 | // output bytes. Fine.
425 | output[op++] = (byte) (value >> 10);
426 | output[op++] = (byte) (value >> 2);
427 | break;
428 | case 4:
429 | // Read one padding '=' when we expected 2. Illegal.
430 | this.state = 6;
431 | return false;
432 | case 5:
433 | // Read all the padding '='s we expected and no more.
434 | // Fine.
435 | break;
436 | }
437 |
438 | this.state = state;
439 | this.op = op;
440 | return true;
441 | }
442 | }
443 |
444 | // --------------------------------------------------------
445 | // encoding
446 | // --------------------------------------------------------
447 |
448 | /**
449 | * Base64-encode the given data and return a newly allocated
450 | * String with the result.
451 | *
452 | * @param input the data to encode
453 | * @param flags controls certain features of the encoded output.
454 | * Passing {@code DEFAULT} results in output that
455 | * adheres to RFC 2045.
456 | */
457 | public static String encodeToString(byte[] input, int flags) {
458 | try {
459 | return new String(encode(input, flags), "US-ASCII");
460 | } catch (UnsupportedEncodingException e) {
461 | // US-ASCII is guaranteed to be available.
462 | throw new AssertionError(e);
463 | }
464 | }
465 |
466 | /**
467 | * Base64-encode the given data and return a newly allocated
468 | * String with the result.
469 | *
470 | * @param input the data to encode
471 | * @param offset the position within the input array at which to
472 | * start
473 | * @param len the number of bytes of input to encode
474 | * @param flags controls certain features of the encoded output.
475 | * Passing {@code DEFAULT} results in output that
476 | * adheres to RFC 2045.
477 | */
478 | public static String encodeToString(byte[] input, int offset, int len,
479 | int flags) {
480 | try {
481 | return new String(encode(input, offset, len, flags), "US-ASCII");
482 | } catch (UnsupportedEncodingException e) {
483 | // US-ASCII is guaranteed to be available.
484 | throw new AssertionError(e);
485 | }
486 | }
487 |
488 | /**
489 | * Base64-encode the given data and return a newly allocated
490 | * byte[] with the result.
491 | *
492 | * @param input the data to encode
493 | * @param flags controls certain features of the encoded output.
494 | * Passing {@code DEFAULT} results in output that
495 | * adheres to RFC 2045.
496 | */
497 | public static byte[] encode(byte[] input, int flags) {
498 | return encode(input, 0, input.length, flags);
499 | }
500 |
501 | /**
502 | * Base64-encode the given data and return a newly allocated
503 | * byte[] with the result.
504 | *
505 | * @param input the data to encode
506 | * @param offset the position within the input array at which to
507 | * start
508 | * @param len the number of bytes of input to encode
509 | * @param flags controls certain features of the encoded output.
510 | * Passing {@code DEFAULT} results in output that
511 | * adheres to RFC 2045.
512 | */
513 | public static byte[] encode(byte[] input, int offset, int len, int flags) {
514 | Encoder encoder = new Encoder(flags, null);
515 |
516 | // Compute the exact length of the array we will produce.
517 | int output_len = len / 3 * 4;
518 |
519 | // Account for the tail of the data and the padding bytes, if any.
520 | if (encoder.do_padding) {
521 | if (len % 3 > 0) {
522 | output_len += 4;
523 | }
524 | } else {
525 | switch (len % 3) {
526 | case 0:
527 | break;
528 | case 1:
529 | output_len += 2;
530 | break;
531 | case 2:
532 | output_len += 3;
533 | break;
534 | }
535 | }
536 |
537 | // Account for the newlines, if any.
538 | if (encoder.do_newline && len > 0) {
539 | output_len += (((len - 1) / (3 * Encoder.LINE_GROUPS)) + 1)
540 | * (encoder.do_cr ? 2 : 1);
541 | }
542 |
543 | encoder.output = new byte[output_len];
544 | encoder.process(input, offset, len, true);
545 |
546 | assert encoder.op == output_len;
547 |
548 | return encoder.output;
549 | }
550 |
551 | /* package */static class Encoder extends Coder {
552 | /**
553 | * Emit a new line every this many output tuples. Corresponds to
554 | * a 76-character line length (the maximum allowable according to
555 | * RFC 2045).
556 | */
557 | public static final int LINE_GROUPS = 19;
558 |
559 | /**
560 | * Lookup table for turning Base64 alphabet positions (6 bits)
561 | * into output bytes.
562 | */
563 | private static final byte ENCODE[] = { 'A', 'B', 'C', 'D', 'E', 'F',
564 | 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
565 | 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
566 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
567 | 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
568 | '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', };
569 |
570 | /**
571 | * Lookup table for turning Base64 alphabet positions (6 bits)
572 | * into output bytes.
573 | */
574 | private static final byte ENCODE_WEBSAFE[] = { 'A', 'B', 'C', 'D', 'E',
575 | 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
576 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
577 | 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
578 | 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
579 | '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', };
580 |
581 | final private byte[] tail;
582 | /* package */int tailLen;
583 | private int count;
584 |
585 | final public boolean do_padding;
586 | final public boolean do_newline;
587 | final public boolean do_cr;
588 | final private byte[] alphabet;
589 |
590 | public Encoder(int flags, byte[] output) {
591 | this.output = output;
592 |
593 | do_padding = (flags & NO_PADDING) == 0;
594 | do_newline = (flags & NO_WRAP) == 0;
595 | do_cr = (flags & CRLF) != 0;
596 | alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE;
597 |
598 | tail = new byte[2];
599 | tailLen = 0;
600 |
601 | count = do_newline ? LINE_GROUPS : -1;
602 | }
603 |
604 | /**
605 | * @return an overestimate for the number of bytes {@code
606 | * len} bytes could encode to.
607 | */
608 | public int maxOutputSize(int len) {
609 | return len * 8 / 5 + 10;
610 | }
611 |
612 | public boolean process(byte[] input, int offset, int len, boolean finish) {
613 | // Using local variables makes the encoder about 9% faster.
614 | final byte[] alphabet = this.alphabet;
615 | final byte[] output = this.output;
616 | int op = 0;
617 | int count = this.count;
618 |
619 | int p = offset;
620 | len += offset;
621 | int v = -1;
622 |
623 | // First we need to concatenate the tail of the previous call
624 | // with any input bytes available now and see if we can empty
625 | // the tail.
626 |
627 | switch (tailLen) {
628 | case 0:
629 | // There was no tail.
630 | break;
631 |
632 | case 1:
633 | if (p + 2 <= len) {
634 | // A 1-byte tail with at least 2 bytes of
635 | // input available now.
636 | v = ((tail[0] & 0xff) << 16) | ((input[p++] & 0xff) << 8)
637 | | (input[p++] & 0xff);
638 | tailLen = 0;
639 | }
640 | ;
641 | break;
642 |
643 | case 2:
644 | if (p + 1 <= len) {
645 | // A 2-byte tail with at least 1 byte of input.
646 | v = ((tail[0] & 0xff) << 16) | ((tail[1] & 0xff) << 8)
647 | | (input[p++] & 0xff);
648 | tailLen = 0;
649 | }
650 | break;
651 | }
652 |
653 | if (v != -1) {
654 | output[op++] = alphabet[(v >> 18) & 0x3f];
655 | output[op++] = alphabet[(v >> 12) & 0x3f];
656 | output[op++] = alphabet[(v >> 6) & 0x3f];
657 | output[op++] = alphabet[v & 0x3f];
658 | if (--count == 0) {
659 | if (do_cr)
660 | output[op++] = '\r';
661 | output[op++] = '\n';
662 | count = LINE_GROUPS;
663 | }
664 | }
665 |
666 | // At this point either there is no tail, or there are fewer
667 | // than 3 bytes of input available.
668 |
669 | // The main loop, turning 3 input bytes into 4 output bytes on
670 | // each iteration.
671 | while (p + 3 <= len) {
672 | v = ((input[p] & 0xff) << 16) | ((input[p + 1] & 0xff) << 8)
673 | | (input[p + 2] & 0xff);
674 | output[op] = alphabet[(v >> 18) & 0x3f];
675 | output[op + 1] = alphabet[(v >> 12) & 0x3f];
676 | output[op + 2] = alphabet[(v >> 6) & 0x3f];
677 | output[op + 3] = alphabet[v & 0x3f];
678 | p += 3;
679 | op += 4;
680 | if (--count == 0) {
681 | if (do_cr)
682 | output[op++] = '\r';
683 | output[op++] = '\n';
684 | count = LINE_GROUPS;
685 | }
686 | }
687 |
688 | if (finish) {
689 | // Finish up the tail of the input. Note that we need to
690 | // consume any bytes in tail before any bytes
691 | // remaining in input; there should be at most two bytes
692 | // total.
693 |
694 | if (p - tailLen == len - 1) {
695 | int t = 0;
696 | v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4;
697 | tailLen -= t;
698 | output[op++] = alphabet[(v >> 6) & 0x3f];
699 | output[op++] = alphabet[v & 0x3f];
700 | if (do_padding) {
701 | output[op++] = '=';
702 | output[op++] = '=';
703 | }
704 | if (do_newline) {
705 | if (do_cr)
706 | output[op++] = '\r';
707 | output[op++] = '\n';
708 | }
709 | } else if (p - tailLen == len - 2) {
710 | int t = 0;
711 | v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10)
712 | | (((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2);
713 | tailLen -= t;
714 | output[op++] = alphabet[(v >> 12) & 0x3f];
715 | output[op++] = alphabet[(v >> 6) & 0x3f];
716 | output[op++] = alphabet[v & 0x3f];
717 | if (do_padding) {
718 | output[op++] = '=';
719 | }
720 | if (do_newline) {
721 | if (do_cr)
722 | output[op++] = '\r';
723 | output[op++] = '\n';
724 | }
725 | } else if (do_newline && op > 0 && count != LINE_GROUPS) {
726 | if (do_cr)
727 | output[op++] = '\r';
728 | output[op++] = '\n';
729 | }
730 |
731 | assert tailLen == 0;
732 | assert p == len;
733 | } else {
734 | // Save the leftovers in tail to be consumed on the next
735 | // call to encodeInternal.
736 |
737 | if (p == len - 1) {
738 | tail[tailLen++] = input[p];
739 | } else if (p == len - 2) {
740 | tail[tailLen++] = input[p];
741 | tail[tailLen++] = input[p + 1];
742 | }
743 | }
744 |
745 | this.op = op;
746 | this.count = count;
747 |
748 | return true;
749 | }
750 | }
751 |
752 | private Base64() {
753 | } // don't instantiate
754 | }
755 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/Crypto.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore;
2 |
3 | import java.io.IOException;
4 | import java.io.UnsupportedEncodingException;
5 | import java.math.BigInteger;
6 | import java.security.GeneralSecurityException;
7 | import java.security.KeyFactory;
8 | import java.security.KeyPair;
9 | import java.security.KeyPairGenerator;
10 | import java.security.NoSuchAlgorithmException;
11 | import java.security.PrivateKey;
12 | import java.security.Provider;
13 | import java.security.Provider.Service;
14 | import java.security.PublicKey;
15 | import java.security.SecureRandom;
16 | import java.security.Security;
17 | import java.security.Signature;
18 | import java.security.interfaces.RSAPublicKey;
19 | import java.security.spec.X509EncodedKeySpec;
20 | import java.util.ArrayList;
21 | import java.util.Calendar;
22 | import java.util.Collections;
23 | import java.util.List;
24 | import java.util.Set;
25 |
26 | import javax.crypto.Cipher;
27 | import javax.crypto.KeyGenerator;
28 | import javax.crypto.SecretKey;
29 | import javax.crypto.spec.IvParameterSpec;
30 | import javax.security.auth.x500.X500Principal;
31 |
32 | import org.spongycastle.asn1.ASN1Encoding;
33 | import org.spongycastle.asn1.DERObjectIdentifier;
34 | import org.spongycastle.asn1.x509.AlgorithmIdentifier;
35 | import org.spongycastle.asn1.x509.DigestInfo;
36 | import org.spongycastle.crypto.CryptoException;
37 | import org.spongycastle.crypto.DataLengthException;
38 | import org.spongycastle.crypto.Digest;
39 | import org.spongycastle.crypto.InvalidCipherTextException;
40 | import org.spongycastle.crypto.digests.SHA512Digest;
41 | import org.spongycastle.crypto.encodings.OAEPEncoding;
42 | import org.spongycastle.crypto.params.RSAKeyParameters;
43 | import org.spongycastle.crypto.signers.PSSSigner;
44 |
45 | import android.annotation.SuppressLint;
46 | import android.content.Context;
47 | import android.security.KeyPairGeneratorSpec;
48 | import android.util.Log;
49 |
50 | public class Crypto {
51 |
52 | private static final String TAG = Crypto.class.getSimpleName();
53 |
54 | private static String DELIMITER = "]";
55 |
56 | private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
57 | private static int KEY_LENGTH = 256;
58 |
59 | private static SecureRandom random = new SecureRandom();
60 |
61 | private Crypto() {
62 | }
63 |
64 | @SuppressLint("DefaultLocale")
65 | public static void listAlgorithms(String algFilter) {
66 | Provider[] providers = Security.getProviders();
67 | for (Provider p : providers) {
68 | String providerStr = String.format("%s/%s/%f\n", p.getName(),
69 | p.getInfo(), p.getVersion());
70 | Log.d(TAG, providerStr);
71 | Set services = p.getServices();
72 | List algs = new ArrayList();
73 | for (Service s : services) {
74 | boolean match = true;
75 | if (algFilter != null) {
76 | match = s.getAlgorithm().toLowerCase()
77 | .contains(algFilter.toLowerCase());
78 | }
79 |
80 | if (match) {
81 | String algStr = String.format("\t%s/%s/%s", s.getType(),
82 | s.getAlgorithm(), s.getClassName());
83 | algs.add(algStr);
84 | }
85 | }
86 |
87 | Collections.sort(algs);
88 | for (String alg : algs) {
89 | Log.d(TAG, "\t" + alg);
90 | }
91 | Log.d(TAG, "");
92 | }
93 | }
94 |
95 | public static SecretKey generateAesKey() {
96 | try {
97 | KeyGenerator kg = KeyGenerator.getInstance("AES");
98 | kg.init(KEY_LENGTH);
99 | SecretKey key = kg.generateKey();
100 |
101 | return key;
102 | } catch (NoSuchAlgorithmException e) {
103 | throw new RuntimeException(e);
104 | }
105 |
106 | }
107 |
108 | public static byte[] generateIv(int length) {
109 | byte[] b = new byte[length];
110 | random.nextBytes(b);
111 |
112 | return b;
113 | }
114 |
115 | public static String encryptAesCbc(String plaintext, SecretKey key) {
116 | try {
117 | Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
118 |
119 | byte[] iv = generateIv(cipher.getBlockSize());
120 | Log.d(TAG, "IV: " + toHex(iv));
121 | IvParameterSpec ivParams = new IvParameterSpec(iv);
122 | cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
123 | Log.d(TAG, "Cipher IV: "
124 | + (cipher.getIV() == null ? null : toHex(cipher.getIV())));
125 | byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
126 |
127 | return String.format("%s%s%s", toBase64(iv), DELIMITER,
128 | toBase64(cipherText));
129 | } catch (GeneralSecurityException e) {
130 | throw new RuntimeException(e);
131 | } catch (UnsupportedEncodingException e) {
132 | throw new RuntimeException(e);
133 | }
134 | }
135 |
136 | public static String encryptRsaOaep(String plaintext, String keyAlias) {
137 | try {
138 | AndroidRsaEngine rsa = new AndroidRsaEngine(keyAlias, false);
139 |
140 | Digest digest = new SHA512Digest();
141 | Digest mgf1digest = new SHA512Digest();
142 | OAEPEncoding oaep = new OAEPEncoding(rsa, digest, mgf1digest, null);
143 | oaep.init(true, null);
144 | byte[] plainBytes = plaintext.getBytes("UTF-8");
145 | byte[] cipherText = oaep.processBlock(plainBytes, 0,
146 | plainBytes.length);
147 |
148 | return toBase64(cipherText);
149 | } catch (UnsupportedEncodingException e) {
150 | throw new RuntimeException(e);
151 | } catch (InvalidCipherTextException e) {
152 | throw new RuntimeException(e);
153 | }
154 | }
155 |
156 | public static String decryptRsaOaep(String ciphertext, String keyAlias) {
157 | try {
158 | AndroidRsaEngine rsa = new AndroidRsaEngine(keyAlias, false);
159 |
160 | Digest digest = new SHA512Digest();
161 | Digest mgf1digest = new SHA512Digest();
162 | OAEPEncoding oaep = new OAEPEncoding(rsa, digest, mgf1digest, null);
163 | oaep.init(false, null);
164 |
165 | byte[] ciphertextBytes = fromBase64(ciphertext);
166 | byte[] plain = oaep.processBlock(ciphertextBytes, 0,
167 | ciphertextBytes.length);
168 |
169 | return new String(plain, "UTF-8");
170 | } catch (UnsupportedEncodingException e) {
171 | throw new RuntimeException(e);
172 | } catch (InvalidCipherTextException e) {
173 | throw new RuntimeException(e);
174 | }
175 | }
176 |
177 | public static String toHex(byte[] bytes) {
178 | StringBuffer buff = new StringBuffer();
179 | for (byte b : bytes) {
180 | buff.append(String.format("%02X", b));
181 | }
182 |
183 | return buff.toString();
184 | }
185 |
186 | public static String toBase64(byte[] bytes) {
187 | return Base64.encodeToString(bytes, Base64.NO_WRAP);
188 | }
189 |
190 | public static byte[] fromBase64(String base64) {
191 | return Base64.decode(base64, Base64.NO_WRAP);
192 | }
193 |
194 | public static String decryptAesCbc(String ciphertext, SecretKey key) {
195 | try {
196 | String[] fields = ciphertext.split(DELIMITER);
197 | if (fields.length != 2) {
198 | throw new IllegalArgumentException(
199 | "Invalid encypted text format");
200 | }
201 |
202 | byte[] iv = fromBase64(fields[0]);
203 | byte[] cipherBytes = fromBase64(fields[1]);
204 | Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
205 | IvParameterSpec ivParams = new IvParameterSpec(iv);
206 | cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
207 | Log.d(TAG, "Cipher IV: " + toHex(cipher.getIV()));
208 | byte[] plaintext = cipher.doFinal(cipherBytes);
209 | String plainrStr = new String(plaintext, "UTF-8");
210 |
211 | return plainrStr;
212 | } catch (GeneralSecurityException e) {
213 | throw new RuntimeException(e);
214 | } catch (UnsupportedEncodingException e) {
215 | throw new RuntimeException(e);
216 | }
217 | }
218 |
219 | public static RSAPublicKey createPublicKey(byte[] pubKeyBytes)
220 | throws GeneralSecurityException {
221 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKeyBytes);
222 | KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
223 | RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpec);
224 |
225 | return pubKey;
226 | }
227 |
228 | @SuppressWarnings("deprecation")
229 | public static byte[] createSha512EncryptionBlock(byte[] digest, int keySize)
230 | throws IOException, InvalidCipherTextException {
231 | // SHA512
232 | DERObjectIdentifier oid = new DERObjectIdentifier(
233 | "2.16.840.1.101.3.4.2.3");
234 | AlgorithmIdentifier sha512Aid = new AlgorithmIdentifier(oid);
235 | DigestInfo di = new DigestInfo(sha512Aid, digest);
236 | byte[] diDer = di.getEncoded(ASN1Encoding.DER);
237 |
238 | return padPkcs1(diDer, keySize);
239 | }
240 |
241 | // PKCS#1 padding
242 | public static byte[] padPkcs1(byte[] in, int keySize) {
243 | if (in.length > keySize) {
244 | throw new IllegalArgumentException("Data too long");
245 | }
246 | byte[] result = new byte[keySize / 8];
247 |
248 | result[0] = 0x0;
249 | result[1] = 0x01; // BT 1
250 |
251 | // PS
252 | for (int i = 2; i != result.length - in.length - 1; i++) {
253 | result[i] = (byte) 0xff;
254 | }
255 |
256 | // end of padding
257 | result[result.length - in.length - 1] = 0x00;
258 | // D
259 | System.arraycopy(in, 0, result, result.length - in.length, in.length);
260 |
261 | return result;
262 | }
263 |
264 | @SuppressLint("NewApi")
265 | public static KeyPair generateRsaPairWithGenerator(Context ctx, String alais)
266 | throws Exception {
267 | Calendar notBefore = Calendar.getInstance();
268 | Calendar notAfter = Calendar.getInstance();
269 | notAfter.add(1, Calendar.YEAR);
270 | KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
271 | .setAlias(alais)
272 | .setSubject(
273 | new X500Principal(String.format("CN=%s, OU=%s", alais,
274 | ctx.getPackageName())))
275 | .setSerialNumber(BigInteger.ONE)
276 | .setStartDate(notBefore.getTime())
277 | .setEndDate(notAfter.getTime()).build();
278 |
279 | KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA",
280 | "AndroidKeyStore");
281 | kpGenerator.initialize(spec);
282 | KeyPair kp = kpGenerator.generateKeyPair();
283 |
284 | return kp;
285 | }
286 |
287 | @SuppressLint("NewApi")
288 | public static KeyPair generateEcPairWithGenerator(Context ctx, String alais)
289 | throws Exception {
290 | Calendar notBefore = Calendar.getInstance();
291 | Calendar notAfter = Calendar.getInstance();
292 | notAfter.add(1, Calendar.YEAR);
293 | KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx)
294 | .setAlias(alais)
295 | .setKeyType("EC")
296 | // curve
297 | .setKeySize(256)
298 | .setSubject(
299 | new X500Principal(String.format("CN=%s, OU=%s", alais,
300 | ctx.getPackageName())))
301 | .setSerialNumber(BigInteger.ONE)
302 | .setStartDate(notBefore.getTime())
303 | .setEndDate(notAfter.getTime()).build();
304 |
305 | KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA",
306 | "AndroidKeyStore");
307 | kpGenerator.initialize(spec);
308 | KeyPair kp = kpGenerator.generateKeyPair();
309 |
310 | return kp;
311 | }
312 |
313 | public static String signRsaPss(String keyAlias, String toSign) {
314 | try {
315 | RSAPublicKey pubKey = loadRsaPublicKey(keyAlias);
316 |
317 | AndroidRsaEngine rsa = new AndroidRsaEngine(keyAlias, true);
318 |
319 | Digest digest = new SHA512Digest();
320 | Digest mgf1digest = new SHA512Digest();
321 | PSSSigner signer = new PSSSigner(rsa, digest, mgf1digest, 512 / 8);
322 | RSAKeyParameters params = new RSAKeyParameters(false,
323 | pubKey.getModulus(), pubKey.getPublicExponent());
324 | signer.init(true, params);
325 |
326 | byte[] signedData = toSign.getBytes("UTF-8");
327 | signer.update(signedData, 0, signedData.length);
328 | byte[] signature = signer.generateSignature();
329 |
330 | return toBase64(signature);
331 | } catch (GeneralSecurityException e) {
332 | throw new RuntimeException(e);
333 | } catch (IOException e) {
334 | throw new RuntimeException(e);
335 | } catch (DataLengthException e) {
336 | throw new RuntimeException(e);
337 | } catch (CryptoException e) {
338 | throw new RuntimeException(e);
339 | }
340 | }
341 |
342 | public static RSAPublicKey loadRsaPublicKey(String keyAlias)
343 | throws GeneralSecurityException, IOException {
344 | return (RSAPublicKey) loadPublicKey(keyAlias);
345 | }
346 |
347 | public static PublicKey loadPublicKey(String keyAlias)
348 | throws GeneralSecurityException, IOException {
349 | java.security.KeyStore ks = java.security.KeyStore
350 | .getInstance("AndroidKeyStore");
351 | ks.load(null);
352 | java.security.KeyStore.Entry keyEntry = ks.getEntry(keyAlias, null);
353 |
354 | return ((java.security.KeyStore.PrivateKeyEntry) keyEntry)
355 | .getCertificate().getPublicKey();
356 | }
357 |
358 | public static PrivateKey loadPrivateKey(String keyAlias)
359 | throws GeneralSecurityException, IOException {
360 | java.security.KeyStore ks = java.security.KeyStore
361 | .getInstance("AndroidKeyStore");
362 | ks.load(null);
363 | java.security.KeyStore.Entry keyEntry = ks.getEntry(keyAlias, null);
364 |
365 | return ((java.security.KeyStore.PrivateKeyEntry) keyEntry)
366 | .getPrivateKey();
367 | }
368 |
369 | public static boolean verifyRsaPss(String signatureStr, String signedStr,
370 | String keyAlias) {
371 | try {
372 | RSAPublicKey pubKey = loadRsaPublicKey(keyAlias);
373 |
374 | AndroidRsaEngine rsa = new AndroidRsaEngine(keyAlias, true);
375 |
376 | Digest digest = new SHA512Digest();
377 | Digest mgf1digest = new SHA512Digest();
378 | PSSSigner signer = new PSSSigner(rsa, digest, mgf1digest, 512 / 8);
379 | RSAKeyParameters params = new RSAKeyParameters(false,
380 | pubKey.getModulus(), pubKey.getPublicExponent());
381 | signer.init(false, params);
382 |
383 | byte[] signedData = signedStr.getBytes("UTF-8");
384 | signer.update(signedData, 0, signedData.length);
385 | byte[] signature = fromBase64(signatureStr);
386 | boolean result = signer.verifySignature(signature);
387 |
388 | return result;
389 | } catch (GeneralSecurityException e) {
390 | throw new RuntimeException(e);
391 | } catch (IOException e) {
392 | throw new RuntimeException(e);
393 | }
394 | }
395 |
396 | public static String signEc(String keyAlias, String toSign) {
397 | try {
398 | PrivateKey privKey = loadPrivateKey(keyAlias);
399 |
400 | Signature sig = Signature.getInstance("SHA512WITHECDSA");
401 | sig.initSign(privKey);
402 | byte[] signedData = toSign.getBytes("UTF-8");
403 | sig.update(signedData);
404 | byte[] signature = sig.sign();
405 |
406 | return toBase64(signature);
407 | } catch (GeneralSecurityException e) {
408 | throw new RuntimeException(e);
409 | } catch (IOException e) {
410 | throw new RuntimeException(e);
411 | } catch (DataLengthException e) {
412 | throw new RuntimeException(e);
413 | }
414 | }
415 |
416 | public static boolean verifyEc(String signatureStr, String signedStr,
417 | String keyAlias) {
418 | try {
419 | PublicKey pubKey = loadPublicKey(keyAlias);
420 |
421 | Signature sig = Signature.getInstance("SHA512WITHECDSA");
422 | sig.initVerify(pubKey);
423 |
424 | byte[] signedData = signedStr.getBytes("UTF-8");
425 | byte[] signature = fromBase64(signatureStr);
426 | sig.update(signedData);
427 | boolean result = sig.verify(signature);
428 |
429 | return result;
430 | } catch (GeneralSecurityException e) {
431 | throw new RuntimeException(e);
432 | } catch (IOException e) {
433 | throw new RuntimeException(e);
434 | }
435 | }
436 |
437 | }
438 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/KeystoreActivity.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore;
2 |
3 | import java.math.BigInteger;
4 | import java.security.KeyPair;
5 | import java.security.interfaces.ECPublicKey;
6 | import java.security.interfaces.RSAPublicKey;
7 |
8 | import javax.crypto.SecretKey;
9 | import javax.crypto.spec.SecretKeySpec;
10 |
11 | import org.nick.androidkeystore.android.security.KeyStore;
12 | import org.nick.androidkeystore.android.security.KeyStoreJb43;
13 | import org.nick.androidkeystore.android.security.KeyStoreKk;
14 |
15 | import android.annotation.SuppressLint;
16 | import android.annotation.TargetApi;
17 | import android.app.Activity;
18 | import android.content.ActivityNotFoundException;
19 | import android.content.Intent;
20 | import android.os.AsyncTask;
21 | import android.os.Build;
22 | import android.os.Bundle;
23 | import android.security.KeyChain;
24 | import android.util.Log;
25 | import android.view.View;
26 | import android.view.View.OnClickListener;
27 | import android.view.Window;
28 | import android.widget.ArrayAdapter;
29 | import android.widget.Button;
30 | import android.widget.ListView;
31 | import android.widget.TextView;
32 | import android.widget.Toast;
33 |
34 | public class KeystoreActivity extends Activity implements OnClickListener {
35 |
36 | private static final String TAG = KeystoreActivity.class.getSimpleName();
37 |
38 | private static final boolean IS_JB43 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
39 | private static final boolean IS_JB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
40 | private static final boolean IS_KK = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
41 |
42 | private static final String EXTRA_CIPHERTEXT = "org.nick.androidkeystore.CIPHERTEXT";
43 | private static final String EXTRA_KEY_NAME = "org.nick.androidkeystore.KEY_NAME";
44 | private static final String EXTRA_PLAINTEXT = "org.nick.androidkeystore.PLAINTEXT";
45 |
46 | public static final String OLD_UNLOCK_ACTION = "android.credentials.UNLOCK";
47 |
48 | public static final String UNLOCK_ACTION = "com.android.credentials.UNLOCK";
49 | public static final String RESET_ACTION = "com.android.credentials.RESET";
50 |
51 | private static final String KEY_NAME = "aes_key";
52 | private static final String RSA_KEY_NAME = "rsa_key";
53 | private static final String EC_KEY_NAME = "ec_key";
54 | private static final String PLAIN_TEXT = "Hello, KeyStore!";
55 |
56 | private static int keyNum = 0;
57 |
58 | private TextView encryptedText;
59 | private TextView decryptedText;
60 |
61 | private Button encryptButton;
62 | private Button decryptButton;
63 | private Button signButton;
64 | private Button verifyButton;
65 | private Button encryptRsaButton;
66 | private Button decryptRsaButton;
67 | private Button signEcButton;
68 | private Button verifyEcButton;
69 | private Button listButton;
70 | private Button resetButton;
71 |
72 | private ListView keyList;
73 |
74 | private KeyStore ks;
75 |
76 | private String encryptionKeyName;
77 | private String signKeyName;
78 | private String rsaEncryptKeyName;
79 |
80 | /** Called when the activity is first created. */
81 | @Override
82 | public void onCreate(Bundle savedInstanceState) {
83 | requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
84 |
85 | super.onCreate(savedInstanceState);
86 |
87 | PRNGFixes.apply();
88 |
89 | setContentView(R.layout.main);
90 |
91 | findViews();
92 |
93 | if (savedInstanceState != null) {
94 | encryptedText.setText(savedInstanceState
95 | .getString(EXTRA_CIPHERTEXT));
96 | encryptionKeyName = savedInstanceState.getString(EXTRA_KEY_NAME);
97 |
98 | String plaintext = savedInstanceState.getString(EXTRA_PLAINTEXT);
99 | decryptedText.setText(plaintext);
100 | }
101 |
102 | if (IS_KK) {
103 | ks = KeyStoreKk.getInstance();
104 | } else if (IS_JB43) {
105 | ks = KeyStoreJb43.getInstance();
106 | } else {
107 | ks = KeyStore.getInstance();
108 | }
109 |
110 | displayKeystoreState();
111 | }
112 |
113 | abstract class KeystoreTask extends AsyncTask {
114 |
115 | Exception error;
116 |
117 | @Override
118 | protected void onPreExecute() {
119 | setProgressBarIndeterminateVisibility(true);
120 | toggleControls(false);
121 | }
122 |
123 | @Override
124 | protected String[] doInBackground(Void... params) {
125 | try {
126 | return doWork();
127 | } catch (Exception e) {
128 | error = e;
129 | Log.e(TAG, "Error: " + e.getMessage(), e);
130 |
131 | return null;
132 | }
133 | }
134 |
135 | protected abstract String[] doWork() throws Exception;
136 |
137 | @Override
138 | protected void onPostExecute(String[] result) {
139 | setProgressBarIndeterminateVisibility(false);
140 | toggleControls(true);
141 |
142 | if (error != null) {
143 | Toast.makeText(KeystoreActivity.this,
144 | "Error: " + error.getMessage(), Toast.LENGTH_LONG)
145 | .show();
146 |
147 | return;
148 | }
149 |
150 | updateUi(result);
151 | }
152 |
153 | protected abstract void updateUi(String[] result);
154 | }
155 |
156 | private void toggleControls(boolean enable) {
157 | encryptButton.setEnabled(enable);
158 | decryptButton.setEnabled(enable);
159 | listButton.setEnabled(enable);
160 | resetButton.setEnabled(enable);
161 | if (IS_JB) {
162 | signButton.setEnabled(enable);
163 | verifyButton.setEnabled(enable);
164 | encryptRsaButton.setEnabled(enable);
165 | decryptRsaButton.setEnabled(enable);
166 | }
167 | if (IS_KK) {
168 | signEcButton.setEnabled(enable);
169 | verifyEcButton.setEnabled(enable);
170 | }
171 | }
172 |
173 | private void displayKeystoreState() {
174 | new KeystoreTask() {
175 |
176 | @Override
177 | protected String[] doWork() {
178 | Log.d(TAG, "Keystore state: " + ks.state());
179 | String status = String.format("Keystore state:%s", ks.state()
180 | .toString());
181 | String storeType = null;
182 | if (IS_KK) {
183 | storeType = ((KeyStoreKk) ks).isHardwareBacked() ? "HW-backed"
184 | : "SW only";
185 | } else if (IS_JB43) {
186 | storeType = ((KeyStoreJb43) ks).isHardwareBacked() ? "HW-backed"
187 | : "SW only";
188 | }
189 |
190 | return new String[] { status, storeType };
191 | }
192 |
193 | @Override
194 | @SuppressLint("NewApi")
195 | protected void updateUi(String[] result) {
196 | setTitle(result[0]);
197 | if (result[1] != null) {
198 | if (IS_JB43) {
199 | getActionBar().setSubtitle(result[1]);
200 | }
201 | }
202 | }
203 | }.execute();
204 | }
205 |
206 | private void findViews() {
207 | encryptedText = (TextView) findViewById(R.id.encrypted_text);
208 | decryptedText = (TextView) findViewById(R.id.decrypted_text);
209 |
210 | encryptButton = (Button) findViewById(R.id.encrypt_button);
211 | encryptButton.setOnClickListener(this);
212 |
213 | decryptButton = (Button) findViewById(R.id.decrypt_button);
214 | decryptButton.setOnClickListener(this);
215 |
216 | signButton = (Button) findViewById(R.id.sign_rsa_button);
217 | signButton.setOnClickListener(this);
218 | signButton.setEnabled(IS_JB);
219 |
220 | verifyButton = (Button) findViewById(R.id.verify_rsa_button);
221 | verifyButton.setOnClickListener(this);
222 | verifyButton.setEnabled(IS_JB);
223 |
224 | encryptRsaButton = (Button) findViewById(R.id.encrypt_rsa_button);
225 | encryptRsaButton.setOnClickListener(this);
226 | encryptRsaButton.setEnabled(IS_JB);
227 |
228 | decryptRsaButton = (Button) findViewById(R.id.decrypt_rsa_button);
229 | decryptRsaButton.setOnClickListener(this);
230 | decryptRsaButton.setEnabled(IS_JB);
231 |
232 | signEcButton = (Button) findViewById(R.id.sign_ec_button);
233 | signEcButton.setOnClickListener(this);
234 | signEcButton.setEnabled(IS_KK);
235 |
236 | verifyEcButton = (Button) findViewById(R.id.verify_ec_button);
237 | verifyEcButton.setOnClickListener(this);
238 | verifyEcButton.setEnabled(IS_KK);
239 |
240 | listButton = (Button) findViewById(R.id.list_button);
241 | listButton.setOnClickListener(this);
242 |
243 | resetButton = (Button) findViewById(R.id.reset_button);
244 | resetButton.setOnClickListener(this);
245 |
246 | keyList = (ListView) findViewById(R.id.key_list);
247 | }
248 |
249 | @TargetApi(18)
250 | @Override
251 | protected void onResume() {
252 | super.onResume();
253 |
254 | displayKeystoreState();
255 |
256 | if (ks.state() == KeyStore.State.UNLOCKED) {
257 | showKeys();
258 | }
259 |
260 | if (IS_KK) {
261 | Log.d(TAG,
262 | "RSA supported " + KeyChain.isKeyAlgorithmSupported("RSA"));
263 | Log.d(TAG, "RSA bound " + KeyChain.isBoundKeyAlgorithm("RSA"));
264 |
265 | Log.d(TAG,
266 | "DSA supported " + KeyChain.isKeyAlgorithmSupported("DSA"));
267 | Log.d(TAG, "DSA bound " + KeyChain.isBoundKeyAlgorithm("DSA"));
268 |
269 | Log.d(TAG, "EC supported " + KeyChain.isKeyAlgorithmSupported("EC"));
270 | Log.d(TAG, "EC bound " + KeyChain.isBoundKeyAlgorithm("EC"));
271 | } else if (IS_JB43) {
272 | Log.d(TAG,
273 | "RSA supported " + KeyChain.isKeyAlgorithmSupported("RSA"));
274 | Log.d(TAG, "RSA bound " + KeyChain.isBoundKeyAlgorithm("RSA"));
275 | }
276 | }
277 |
278 | @Override
279 | protected void onSaveInstanceState(Bundle outState) {
280 | super.onSaveInstanceState(outState);
281 |
282 | String ciphertext = encryptedText.getText().toString();
283 | String plaintext = decryptedText.getText().toString();
284 | if (ciphertext != null) {
285 | outState.putString(EXTRA_CIPHERTEXT, encryptedText.getText()
286 | .toString());
287 | outState.putString(EXTRA_KEY_NAME, encryptionKeyName);
288 | }
289 | if (plaintext != null) {
290 | outState.putString(EXTRA_PLAINTEXT, plaintext);
291 | }
292 |
293 | }
294 |
295 | @Override
296 | public void onClick(View v) {
297 | if (ks.state() != KeyStore.State.UNLOCKED) {
298 | Toast.makeText(
299 | this,
300 | "Keystore is locked or not initialized. Retry operation "
301 | + "after unlock activity returns.",
302 | Toast.LENGTH_LONG).show();
303 | unlock();
304 |
305 | // unlocking is in a separate activity, stop here
306 | return;
307 | }
308 |
309 | try {
310 | if (v.getId() == R.id.reset_button) {
311 | deleteAllKeys();
312 | // resetKeystore();
313 | } else if (v.getId() == R.id.list_button) {
314 | showKeys();
315 | // testKeystore();
316 | } else if (v.getId() == R.id.encrypt_button) {
317 | encrypt();
318 | } else if (v.getId() == R.id.decrypt_button) {
319 | if (encryptedText.getText() == null
320 | || encryptedText.getText().equals("")) {
321 | Toast.makeText(this, "No encrypted text found.",
322 | Toast.LENGTH_SHORT).show();
323 |
324 | return;
325 | }
326 |
327 | decrypt();
328 | } else if (v.getId() == R.id.sign_rsa_button) {
329 | signRsaPss();
330 | } else if (v.getId() == R.id.verify_rsa_button) {
331 | verifyRsaPss();
332 | } else if (v.getId() == R.id.encrypt_rsa_button) {
333 | encryptRsaOaep();
334 | } else if (v.getId() == R.id.decrypt_rsa_button) {
335 | decryptRsa();
336 | } else if (v.getId() == R.id.sign_ec_button) {
337 | signEcDsa();
338 | } else if (v.getId() == R.id.verify_ec_button) {
339 | verifyEcDsa();
340 | }
341 | } catch (Exception e) {
342 | Log.e(TAG, "Unexpected error: " + e.getMessage(), e);
343 | Toast.makeText(this, "Unexpected error: " + e.getMessage(),
344 | Toast.LENGTH_LONG).show();
345 | }
346 | }
347 |
348 | private void encryptRsaOaep() {
349 | new KeystoreTask() {
350 |
351 | @Override
352 | protected String[] doWork() throws Exception {
353 | String alias = RSA_KEY_NAME + keyNum;
354 |
355 | KeyPair kp = Crypto.generateRsaPairWithGenerator(
356 | KeystoreActivity.this, alias);
357 | Log.d(TAG, String.format("Genarated %d bit RSA key pair",
358 | ((RSAPublicKey) kp.getPublic()).getModulus()
359 | .bitLength()));
360 | rsaEncryptKeyName = alias;
361 | keyNum++;
362 |
363 | String ciphertext = Crypto.encryptRsaOaep(PLAIN_TEXT,
364 | rsaEncryptKeyName);
365 |
366 | return new String[] { ciphertext };
367 | }
368 |
369 | @Override
370 | protected void updateUi(String[] result) {
371 | encryptedText.setText(result[0]);
372 | decryptedText.setText("");
373 |
374 | showKeys();
375 |
376 | }
377 | }.execute();
378 | }
379 |
380 | private void decryptRsa() {
381 | new KeystoreTask() {
382 |
383 | @Override
384 | protected String[] doWork() throws Exception {
385 | String plainStr = Crypto.decryptRsaOaep(encryptedText.getText()
386 | .toString(), rsaEncryptKeyName);
387 |
388 | return new String[] { plainStr };
389 | }
390 |
391 | @Override
392 | protected void updateUi(String[] result) {
393 | decryptedText.setText(result[0]);
394 |
395 | showKeys();
396 |
397 | }
398 | }.execute();
399 | }
400 |
401 | private void decrypt() {
402 | final String ciphertext = encryptedText.getText().toString();
403 | new KeystoreTask() {
404 |
405 | @Override
406 | protected String[] doWork() {
407 | byte[] keyBytes = ks.get(encryptionKeyName);
408 | if (keyBytes == null) {
409 | Log.w(TAG, "Encryption key not found in keystore: "
410 | + encryptionKeyName);
411 |
412 | return null;
413 | }
414 |
415 | SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
416 | String plaintext = Crypto.decryptAesCbc(ciphertext, key);
417 |
418 | return new String[] { plaintext };
419 | }
420 |
421 | @Override
422 | protected void updateUi(String[] result) {
423 | if (result == null) {
424 | Toast.makeText(KeystoreActivity.this,
425 | "Encryption key not found in keystore.",
426 | Toast.LENGTH_SHORT).show();
427 |
428 | return;
429 | }
430 |
431 | decryptedText.setText(result[0]);
432 | }
433 | }.execute();
434 | }
435 |
436 | private void encrypt() {
437 | new KeystoreTask() {
438 |
439 | @Override
440 | protected String[] doWork() {
441 | SecretKey key = Crypto.generateAesKey();
442 | encryptionKeyName = KEY_NAME + keyNum;
443 | boolean success = ks.put(encryptionKeyName, key.getEncoded());
444 | Log.d(TAG, "put key success: " + success);
445 | checkRc(success);
446 |
447 | keyNum++;
448 | String ciphertext = Crypto.encryptAesCbc(PLAIN_TEXT, key);
449 |
450 | return new String[] { ciphertext };
451 | }
452 |
453 | @Override
454 | protected void updateUi(String[] result) {
455 | encryptedText.setText(result[0]);
456 | decryptedText.setText("");
457 |
458 | showKeys();
459 |
460 | }
461 | }.execute();
462 | }
463 |
464 | private void signRsaPss() {
465 | new KeystoreTask() {
466 |
467 | @Override
468 | protected String[] doWork() throws Exception {
469 | String alias = RSA_KEY_NAME + keyNum;
470 | KeyPair kp = Crypto.generateRsaPairWithGenerator(
471 | KeystoreActivity.this, alias);
472 | Log.d(TAG, String.format("Genarated %d bit RSA key pair",
473 | ((RSAPublicKey) kp.getPublic()).getModulus()
474 | .bitLength()));
475 | signKeyName = alias;
476 | keyNum++;
477 |
478 | String signature = Crypto.signRsaPss(signKeyName, PLAIN_TEXT);
479 |
480 | return new String[] { signature };
481 | }
482 |
483 | @Override
484 | protected void updateUi(String[] result) {
485 | encryptedText.setText(result[0]);
486 | decryptedText.setText("");
487 |
488 | showKeys();
489 |
490 | }
491 | }.execute();
492 | }
493 |
494 | private void verifyRsaPss() {
495 | new KeystoreTask() {
496 |
497 | @Override
498 | protected String[] doWork() throws Exception {
499 | String signatureStr = encryptedText.getText().toString();
500 | boolean verified = Crypto.verifyRsaPss(signatureStr,
501 | PLAIN_TEXT, signKeyName);
502 | Log.d(TAG, "RSA PSS signature verification result: " + verified);
503 |
504 | return new String[] { verified ? "Signature verifies"
505 | : "Invalid signature" };
506 | }
507 |
508 | @Override
509 | protected void updateUi(String[] result) {
510 | if (result == null) {
511 | Toast.makeText(KeystoreActivity.this,
512 | "Signature key key not found in keystore.",
513 | Toast.LENGTH_SHORT).show();
514 |
515 | return;
516 | }
517 |
518 | decryptedText.setText(result[0]);
519 | }
520 | }.execute();
521 | }
522 |
523 | private void signEcDsa() {
524 | new KeystoreTask() {
525 |
526 | @Override
527 | protected String[] doWork() throws Exception {
528 | String alias = EC_KEY_NAME + keyNum;
529 | KeyPair kp = Crypto.generateEcPairWithGenerator(
530 | KeystoreActivity.this, alias);
531 | Log.d(TAG, String.format("Genarated %d bit EC key pair",
532 | ((ECPublicKey) kp.getPublic()).getParams().getCurve()
533 | .getField().getFieldSize()));
534 | signKeyName = alias;
535 | keyNum++;
536 |
537 | String signature = Crypto.signEc(signKeyName, PLAIN_TEXT);
538 |
539 | return new String[] { signature };
540 | }
541 |
542 | @Override
543 | protected void updateUi(String[] result) {
544 | encryptedText.setText(result[0]);
545 | decryptedText.setText("");
546 |
547 | showKeys();
548 |
549 | }
550 | }.execute();
551 | }
552 |
553 | private void verifyEcDsa() {
554 | new KeystoreTask() {
555 |
556 | @Override
557 | protected String[] doWork() throws Exception {
558 | String signatureStr = encryptedText.getText().toString();
559 | boolean verified = Crypto.verifyEc(signatureStr, PLAIN_TEXT,
560 | signKeyName);
561 | Log.d(TAG, "RSA PSS signature verification result: " + verified);
562 |
563 | return new String[] { verified ? "Signature verifies"
564 | : "Invalid signature" };
565 | }
566 |
567 | @Override
568 | protected void updateUi(String[] result) {
569 | if (result == null) {
570 | Toast.makeText(KeystoreActivity.this,
571 | "Signature key key not found in keystore.",
572 | Toast.LENGTH_SHORT).show();
573 |
574 | return;
575 | }
576 |
577 | decryptedText.setText(result[0]);
578 | }
579 | }.execute();
580 | }
581 |
582 | private void deleteAllKeys() {
583 | new KeystoreTask() {
584 |
585 | @Override
586 | protected String[] doWork() throws Exception {
587 | String[] keys = ks.saw("");
588 | for (String key : keys) {
589 | boolean success = ks.delete(key);
590 | Log.d(TAG, String.format("delete key '%s' success: %s",
591 | key, success));
592 | if (!success && IS_JB) {
593 | success = ks.delKey(key);
594 | Log.d(TAG, String.format("delKey '%s' success: %s",
595 | key, success));
596 | }
597 | // delete_keypair() is optional, don't fail
598 | // checkRc(success);
599 | }
600 |
601 | return null;
602 | }
603 |
604 | @Override
605 | protected void updateUi(String[] result) {
606 | encryptionKeyName = null;
607 | signKeyName = null;
608 |
609 | encryptedText.setText("");
610 | decryptedText.setText("");
611 |
612 | showKeys();
613 | }
614 | }.execute();
615 | }
616 |
617 | private void showKeys() {
618 | new KeystoreTask() {
619 |
620 | @Override
621 | protected String[] doWork() {
622 | String[] keyNames = ks.saw("");
623 |
624 | return keyNames;
625 | }
626 |
627 | @Override
628 | protected void updateUi(String[] keyNames) {
629 | ArrayAdapter adapter = new ArrayAdapter(
630 | KeystoreActivity.this,
631 | android.R.layout.simple_list_item_1, keyNames);
632 | keyList.setAdapter(adapter);
633 |
634 | Log.d(TAG, "Keys: ");
635 | for (String keyName : keyNames) {
636 | byte[] keyBytes = ks.get(keyName);
637 |
638 | if (keyBytes != null) {
639 | Log.d(TAG, String.format("\t%s: %s", keyName,
640 | new BigInteger(keyBytes).toString()));
641 | } else {
642 | Log.d(TAG, String.format("\t%s: %s", keyName,
643 | "RSA unexportable"));
644 | }
645 | }
646 | }
647 | }.execute();
648 | }
649 |
650 | private void unlock() {
651 | if (ks.state() == KeyStore.State.UNLOCKED) {
652 | return;
653 | }
654 |
655 | try {
656 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
657 | startActivity(new Intent(OLD_UNLOCK_ACTION));
658 | } else {
659 | startActivity(new Intent(UNLOCK_ACTION));
660 | }
661 | } catch (ActivityNotFoundException e) {
662 | Log.e(TAG, "No UNLOCK activity: " + e.getMessage(), e);
663 | Toast.makeText(this, "No keystore unlock activity found.",
664 | Toast.LENGTH_SHORT).show();
665 |
666 | return;
667 | }
668 | }
669 |
670 | @SuppressWarnings("unused")
671 | private void resetKeystore() {
672 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
673 | Toast.makeText(this, "Reset not supported on pre-ICS devices",
674 | Toast.LENGTH_SHORT).show();
675 | } else {
676 | startActivity(new Intent(RESET_ACTION));
677 | }
678 | }
679 |
680 | @SuppressWarnings("unused")
681 | private void testKeystore() {
682 | boolean success = ks.lock();
683 | if (!success) {
684 | Log.d(TAG, "lock() last error = " + rcToStr(ks.getLastError()));
685 | }
686 | success = ks.unlock("foo");
687 | if (!success) {
688 | Log.d(TAG, "unlock() last error = " + rcToStr(ks.getLastError()));
689 | }
690 | success = ks.password("foobar");
691 | if (!success) {
692 | Log.d(TAG, "password() last error = " + rcToStr(ks.getLastError()));
693 | }
694 | success = ks.reset();
695 | if (!success) {
696 | Log.d(TAG, "reset() last error = " + rcToStr(ks.getLastError()));
697 | }
698 | success = ks.isEmpty();
699 | if (!success) {
700 | Log.d(TAG, "isEmpty() last error = " + rcToStr(ks.getLastError()));
701 | }
702 | }
703 |
704 | private void checkRc(boolean success) {
705 | if (!success) {
706 | String errorStr = rcToStr(ks.getLastError());
707 | Log.d(TAG, "last error = " + errorStr);
708 |
709 | throw new RuntimeException("Keystore error: " + errorStr);
710 | }
711 | }
712 |
713 | private static final String rcToStr(int rc) {
714 | switch (rc) {
715 | case KeyStore.NO_ERROR:
716 | return "NO_ERROR";
717 | case KeyStore.LOCKED:
718 | return "LOCKED";
719 | case KeyStore.UNINITIALIZED:
720 | return "UNINITIALIZED";
721 | case KeyStore.SYSTEM_ERROR:
722 | return "SYSTEM_ERROR";
723 | case KeyStore.PROTOCOL_ERROR:
724 | return "PROTOCOL_ERROR";
725 | case KeyStore.PERMISSION_DENIED:
726 | return "PERMISSION_DENIED";
727 | case KeyStore.KEY_NOT_FOUND:
728 | return "KEY_NOT_FOUND";
729 | case KeyStore.VALUE_CORRUPTED:
730 | return "VALUE_CORRUPTED";
731 | case KeyStore.UNDEFINED_ACTION:
732 | return "UNDEFINED_ACTION";
733 | case KeyStore.WRONG_PASSWORD:
734 | return "WRONG_PASSWORD";
735 | default:
736 | return "Unknown RC";
737 | }
738 | }
739 | }
740 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/PRNGFixes.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.DataOutputStream;
5 | import java.io.IOException;
6 | import java.io.UnsupportedEncodingException;
7 |
8 | import android.os.Build;
9 | import android.os.Process;
10 |
11 | // Based on http://android-developers.blogspot.jp/2013/08/some-securerandom-thoughts.html
12 | public class PRNGFixes {
13 |
14 | private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial();
15 |
16 | private PRNGFixes() {
17 | }
18 |
19 | public static void apply() {
20 | applyOpenSSLFix();
21 | }
22 |
23 | public static void applyOpenSSLFix() throws SecurityException {
24 | if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
25 | || (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2)) {
26 | // No need to apply the fix
27 | return;
28 | }
29 |
30 | try {
31 | // Mix in the device- and invocation-specific seed.
32 | Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
33 | .getMethod("RAND_seed", byte[].class)
34 | .invoke(null, generateSeed());
35 |
36 | // Mix output of Linux PRNG into OpenSSL's PRNG
37 | int bytesRead = (Integer) Class
38 | .forName(
39 | "org.apache.harmony.xnet.provider.jsse.NativeCrypto")
40 | .getMethod("RAND_load_file", String.class, long.class)
41 | .invoke(null, "/dev/urandom", 1024);
42 | if (bytesRead != 1024) {
43 | throw new IOException(
44 | "Unexpected number of bytes read from Linux PRNG: "
45 | + bytesRead);
46 | }
47 | } catch (Exception e) {
48 | throw new SecurityException("Failed to seed OpenSSL PRNG", e);
49 | }
50 | }
51 |
52 | private static byte[] generateSeed() {
53 | try {
54 | ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
55 | DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer);
56 | seedBufferOut.writeLong(System.currentTimeMillis());
57 | seedBufferOut.writeLong(System.nanoTime());
58 | seedBufferOut.writeInt(Process.myPid());
59 | seedBufferOut.writeInt(Process.myUid());
60 | seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
61 | seedBufferOut.close();
62 | return seedBuffer.toByteArray();
63 | } catch (IOException e) {
64 | throw new SecurityException("Failed to generate seed", e);
65 | }
66 | }
67 |
68 | private static String getDeviceSerialNumber() {
69 | // We're using the Reflection API because Build.SERIAL is only available
70 | // since API Level 9 (Gingerbread, Android 2.3).
71 | try {
72 | return (String) Build.class.getField("SERIAL").get(null);
73 | } catch (Exception ignored) {
74 | return null;
75 | }
76 | }
77 |
78 | private static byte[] getBuildFingerprintAndDeviceSerial() {
79 | StringBuilder result = new StringBuilder();
80 | String fingerprint = Build.FINGERPRINT;
81 | if (fingerprint != null) {
82 | result.append(fingerprint);
83 | }
84 | String serial = getDeviceSerialNumber();
85 | if (serial != null) {
86 | result.append(serial);
87 | }
88 | try {
89 | return result.toString().getBytes("UTF-8");
90 | } catch (UnsupportedEncodingException e) {
91 | throw new RuntimeException("UTF-8 encoding not supported");
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/android/security/KeyStore.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore.android.security;
2 |
3 | /*
4 | * Copyright (C) 2009 The Android Open Source Project
5 | *
6 | * Licensed under the Apache License, Version 2.0 (the "License");
7 | * you may not use this file except in compliance with the License.
8 | * You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing, software
13 | * distributed under the License is distributed on an "AS IS" BASIS,
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | * See the License for the specific language governing permissions and
16 | * limitations under the License.
17 | */
18 |
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 | import java.io.OutputStream;
22 | import java.io.UnsupportedEncodingException;
23 | import java.util.ArrayList;
24 |
25 | import android.net.LocalSocket;
26 | import android.net.LocalSocketAddress;
27 |
28 | /**
29 | * @hide This should not be made public in its present form because it
30 | * assumes that private and secret key bytes are available and would
31 | * preclude the use of hardware crypto.
32 | */
33 | public class KeyStore {
34 |
35 | // ResponseCodes
36 | public static final int NO_ERROR = 1;
37 | public static final int LOCKED = 2;
38 | public static final int UNINITIALIZED = 3;
39 | public static final int SYSTEM_ERROR = 4;
40 | public static final int PROTOCOL_ERROR = 5;
41 | public static final int PERMISSION_DENIED = 6;
42 | public static final int KEY_NOT_FOUND = 7;
43 | public static final int VALUE_CORRUPTED = 8;
44 | public static final int UNDEFINED_ACTION = 9;
45 | public static final int WRONG_PASSWORD = 10;
46 |
47 | // States
48 | public enum State {
49 | UNLOCKED, LOCKED, UNINITIALIZED
50 | };
51 |
52 | private static final LocalSocketAddress sAddress = new LocalSocketAddress(
53 | "keystore", LocalSocketAddress.Namespace.RESERVED);
54 |
55 | private int mError = NO_ERROR;
56 |
57 | KeyStore() {
58 | }
59 |
60 | public static KeyStore getInstance() {
61 | return new KeyStore();
62 | }
63 |
64 | public State state() {
65 | execute('t');
66 | switch (mError) {
67 | case NO_ERROR:
68 | return State.UNLOCKED;
69 | case LOCKED:
70 | return State.LOCKED;
71 | case UNINITIALIZED:
72 | return State.UNINITIALIZED;
73 | default:
74 | throw new AssertionError(mError);
75 | }
76 | }
77 |
78 | private byte[] get(byte[] key) {
79 | ArrayList values = execute('g', key);
80 | return (values == null || values.isEmpty()) ? null : values.get(0);
81 | }
82 |
83 | public byte[] get(String key) {
84 | return get(getBytes(key));
85 | }
86 |
87 | private boolean put(byte[] key, byte[] value) {
88 | execute('i', key, value);
89 | return mError == NO_ERROR;
90 | }
91 |
92 | public boolean put(String key, byte[] value) {
93 | return put(getBytes(key), value);
94 | }
95 |
96 | private boolean delete(byte[] key) {
97 | execute('d', key);
98 | return mError == NO_ERROR;
99 | }
100 |
101 | public boolean delete(String key) {
102 | return delete(getBytes(key));
103 | }
104 |
105 | private boolean contains(byte[] key) {
106 | execute('e', key);
107 | return mError == NO_ERROR;
108 | }
109 |
110 | public boolean contains(String key) {
111 | return contains(getBytes(key));
112 | }
113 |
114 | public byte[][] saw(byte[] prefix) {
115 | ArrayList values = execute('s', prefix);
116 | return (values == null) ? null : values
117 | .toArray(new byte[values.size()][]);
118 | }
119 |
120 | public String[] saw(String prefix) {
121 | byte[][] values = saw(getBytes(prefix));
122 | if (values == null) {
123 | return null;
124 | }
125 | String[] strings = new String[values.length];
126 | for (int i = 0; i < values.length; ++i) {
127 | strings[i] = toString(values[i]);
128 | }
129 | return strings;
130 | }
131 |
132 | public boolean reset() {
133 | execute('r');
134 | return mError == NO_ERROR;
135 | }
136 |
137 | private boolean password(byte[] password) {
138 | execute('p', password);
139 | return mError == NO_ERROR;
140 | }
141 |
142 | public boolean password(String password) {
143 | return password(getBytes(password));
144 | }
145 |
146 | public boolean lock() {
147 | execute('l');
148 | return mError == NO_ERROR;
149 | }
150 |
151 | private boolean unlock(byte[] password) {
152 | execute('u', password);
153 | return mError == NO_ERROR;
154 | }
155 |
156 | public boolean unlock(String password) {
157 | return unlock(getBytes(password));
158 | }
159 |
160 | public boolean isEmpty() {
161 | execute('z');
162 | return mError == KEY_NOT_FOUND;
163 | }
164 |
165 | private boolean generate(byte[] key) {
166 | execute('a', key);
167 | return mError == NO_ERROR;
168 | }
169 |
170 | public boolean generate(String key) {
171 | return generate(getBytes(key));
172 | }
173 |
174 | private boolean importKey(byte[] keyName, byte[] key) {
175 | execute('m', keyName, key);
176 | return mError == NO_ERROR;
177 | }
178 |
179 | public boolean importKey(String keyName, byte[] key) {
180 | return importKey(getBytes(keyName), key);
181 | }
182 |
183 | private byte[] getPubkey(byte[] key) {
184 | ArrayList values = execute('b', key);
185 | return (values == null || values.isEmpty()) ? null : values.get(0);
186 | }
187 |
188 | public byte[] getPubkey(String key) {
189 | return getPubkey(getBytes(key));
190 | }
191 |
192 | private boolean delKey(byte[] key) {
193 | execute('k', key);
194 | return mError == NO_ERROR;
195 | }
196 |
197 | public boolean delKey(String key) {
198 | return delKey(getBytes(key));
199 | }
200 |
201 | private byte[] sign(byte[] keyName, byte[] data) {
202 | final ArrayList values = execute('n', keyName, data);
203 | return (values == null || values.isEmpty()) ? null : values.get(0);
204 | }
205 |
206 | public byte[] sign(String key, byte[] data) {
207 | return sign(getBytes(key), data);
208 | }
209 |
210 | private boolean verify(byte[] keyName, byte[] data, byte[] signature) {
211 | execute('v', keyName, data, signature);
212 | return mError == NO_ERROR;
213 | }
214 |
215 | public boolean verify(String key, byte[] data, byte[] signature) {
216 | return verify(getBytes(key), data, signature);
217 | }
218 |
219 | private boolean grant(byte[] key, byte[] uid) {
220 | execute('x', key, uid);
221 | return mError == NO_ERROR;
222 | }
223 |
224 | public boolean grant(String key, int uid) {
225 | return grant(getBytes(key), Integer.toString(uid).getBytes());
226 | }
227 |
228 | private boolean ungrant(byte[] key, byte[] uid) {
229 | execute('y', key, uid);
230 | return mError == NO_ERROR;
231 | }
232 |
233 | public boolean ungrant(String key, int uid) {
234 | return ungrant(getBytes(key), Integer.toString(uid).getBytes());
235 | }
236 |
237 | public int getLastError() {
238 | return mError;
239 | }
240 |
241 | private ArrayList execute(int code, byte[]... parameters) {
242 | mError = PROTOCOL_ERROR;
243 |
244 | for (byte[] parameter : parameters) {
245 | if (parameter == null || parameter.length > 65535) {
246 | return null;
247 | }
248 | }
249 |
250 | LocalSocket socket = new LocalSocket();
251 | try {
252 | socket.connect(sAddress);
253 |
254 | OutputStream out = socket.getOutputStream();
255 | out.write(code);
256 | for (byte[] parameter : parameters) {
257 | out.write(parameter.length >> 8);
258 | out.write(parameter.length);
259 | out.write(parameter);
260 | }
261 | out.flush();
262 | socket.shutdownOutput();
263 |
264 | InputStream in = socket.getInputStream();
265 | if ((code = in.read()) != NO_ERROR) {
266 | if (code != -1) {
267 | mError = code;
268 | }
269 | return null;
270 | }
271 |
272 | ArrayList values = new ArrayList();
273 | while (true) {
274 | int i, j;
275 | if ((i = in.read()) == -1) {
276 | break;
277 | }
278 | if ((j = in.read()) == -1) {
279 | return null;
280 | }
281 | byte[] value = new byte[i << 8 | j];
282 | for (i = 0; i < value.length; i += j) {
283 | if ((j = in.read(value, i, value.length - i)) == -1) {
284 | return null;
285 | }
286 | }
287 | values.add(value);
288 | }
289 | mError = NO_ERROR;
290 | return values;
291 | } catch (IOException e) {
292 | // ignore
293 | } finally {
294 | try {
295 | socket.close();
296 | } catch (IOException e) {
297 | }
298 | }
299 | return null;
300 | }
301 |
302 | private static byte[] getBytes(String string) {
303 | try {
304 | return string.getBytes("UTF-8");
305 | } catch (UnsupportedEncodingException e) {
306 | throw new RuntimeException(e);
307 | }
308 | }
309 |
310 | private static String toString(byte[] bytes) {
311 | try {
312 | return new String(bytes, "UTF-8");
313 | } catch (UnsupportedEncodingException e) {
314 | throw new RuntimeException(e);
315 | }
316 | }
317 | }
318 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/android/security/KeyStoreJb43.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | //package android.security;
18 |
19 | package org.nick.androidkeystore.android.security;
20 |
21 | import java.lang.reflect.InvocationTargetException;
22 | import java.lang.reflect.Method;
23 |
24 | import android.os.IBinder;
25 | import android.os.RemoteException;
26 | import android.security.IKeystoreService;
27 | import android.util.Log;
28 |
29 | /**
30 | * @hide This should not be made public in its present form because it assumes
31 | * that private and secret key bytes are available and would preclude the
32 | * use of hardware crypto.
33 | */
34 | public class KeyStoreJb43 extends KeyStore {
35 | private static final String TAG = "KeyStore";
36 |
37 | // ResponseCodes
38 | public static final int NO_ERROR = 1;
39 | public static final int LOCKED = 2;
40 | public static final int UNINITIALIZED = 3;
41 | public static final int SYSTEM_ERROR = 4;
42 | public static final int PROTOCOL_ERROR = 5;
43 | public static final int PERMISSION_DENIED = 6;
44 | public static final int KEY_NOT_FOUND = 7;
45 | public static final int VALUE_CORRUPTED = 8;
46 | public static final int UNDEFINED_ACTION = 9;
47 | public static final int WRONG_PASSWORD = 10;
48 |
49 | // Used for UID field to indicate the calling UID.
50 | public static final int UID_SELF = -1;
51 |
52 | // Flags for "put" "import" and "generate"
53 | public static final int FLAG_NONE = 0;
54 | public static final int FLAG_ENCRYPTED = 1;
55 |
56 | // // States
57 | // public enum State {
58 | // UNLOCKED, LOCKED, UNINITIALIZED
59 | // };
60 |
61 | private int mError = NO_ERROR;
62 |
63 | private final IKeystoreService mBinder;
64 |
65 | private KeyStoreJb43(IKeystoreService binder) {
66 | mBinder = binder;
67 | }
68 |
69 | public static KeyStoreJb43 getInstance() {
70 | try {
71 | Class> smClass = Class.forName("android.os.ServiceManager");
72 |
73 | Method getService = smClass.getMethod("getService", String.class);
74 | IBinder binder = (IBinder) getService.invoke(null,
75 | "android.security.keystore");
76 | IKeystoreService keystore = IKeystoreService.Stub
77 | .asInterface(binder);
78 | return new KeyStoreJb43(keystore);
79 | } catch (ClassNotFoundException e) {
80 | throw new RuntimeException(e);
81 | } catch (NoSuchMethodException e) {
82 | throw new RuntimeException(e);
83 | } catch (IllegalArgumentException e) {
84 | throw new RuntimeException(e);
85 | } catch (IllegalAccessException e) {
86 | throw new RuntimeException(e);
87 | } catch (InvocationTargetException e) {
88 | throw new RuntimeException(e);
89 | }
90 | }
91 |
92 | public State state() {
93 | final int ret;
94 | try {
95 | ret = mBinder.test();
96 | } catch (RemoteException e) {
97 | Log.w(TAG, "Cannot connect to keystore", e);
98 | throw new AssertionError(e);
99 | }
100 |
101 | switch (ret) {
102 | case NO_ERROR:
103 | return State.UNLOCKED;
104 | case LOCKED:
105 | return State.LOCKED;
106 | case UNINITIALIZED:
107 | return State.UNINITIALIZED;
108 | default:
109 | throw new AssertionError(mError);
110 | }
111 | }
112 |
113 | public boolean isUnlocked() {
114 | return state() == State.UNLOCKED;
115 | }
116 |
117 | public byte[] get(String key) {
118 | try {
119 | return mBinder.get(key);
120 | } catch (RemoteException e) {
121 | Log.w(TAG, "Cannot connect to keystore", e);
122 | return null;
123 | }
124 | }
125 |
126 | @Override
127 | public boolean put(String key, byte[] value) {
128 | return put(key, value, UID_SELF, FLAG_ENCRYPTED);
129 | }
130 |
131 | public boolean put(String key, byte[] value, int uid, int flags) {
132 | try {
133 | return mBinder.insert(key, value, uid, flags) == NO_ERROR;
134 | } catch (RemoteException e) {
135 | Log.w(TAG, "Cannot connect to keystore", e);
136 | return false;
137 | }
138 | }
139 |
140 | public boolean delete(String key, int uid) {
141 | try {
142 | return mBinder.del(key, uid) == NO_ERROR;
143 | } catch (RemoteException e) {
144 | Log.w(TAG, "Cannot connect to keystore", e);
145 | return false;
146 | }
147 | }
148 |
149 | public boolean delete(String key) {
150 | return delete(key, UID_SELF);
151 | }
152 |
153 | public boolean contains(String key, int uid) {
154 | try {
155 | return mBinder.exist(key, uid) == NO_ERROR;
156 | } catch (RemoteException e) {
157 | Log.w(TAG, "Cannot connect to keystore", e);
158 | return false;
159 | }
160 | }
161 |
162 | public boolean contains(String key) {
163 | return contains(key, UID_SELF);
164 | }
165 |
166 | public String[] saw(String prefix, int uid) {
167 | try {
168 | return mBinder.saw(prefix, uid);
169 | } catch (RemoteException e) {
170 | Log.w(TAG, "Cannot connect to keystore", e);
171 | return null;
172 | }
173 | }
174 |
175 | public String[] saw(String prefix) {
176 | return saw(prefix, UID_SELF);
177 | }
178 |
179 | public boolean reset() {
180 | try {
181 | return mBinder.reset() == NO_ERROR;
182 | } catch (RemoteException e) {
183 | Log.w(TAG, "Cannot connect to keystore", e);
184 | return false;
185 | }
186 | }
187 |
188 | public boolean password(String password) {
189 | try {
190 | return mBinder.password(password) == NO_ERROR;
191 | } catch (RemoteException e) {
192 | Log.w(TAG, "Cannot connect to keystore", e);
193 | return false;
194 | }
195 | }
196 |
197 | public boolean lock() {
198 | try {
199 | return mBinder.lock() == NO_ERROR;
200 | } catch (RemoteException e) {
201 | Log.w(TAG, "Cannot connect to keystore", e);
202 | return false;
203 | }
204 | }
205 |
206 | public boolean unlock(String password) {
207 | try {
208 | mError = mBinder.unlock(password);
209 | return mError == NO_ERROR;
210 | } catch (RemoteException e) {
211 | Log.w(TAG, "Cannot connect to keystore", e);
212 | return false;
213 | }
214 | }
215 |
216 | public boolean isEmpty() {
217 | try {
218 | return mBinder.zero() == KEY_NOT_FOUND;
219 | } catch (RemoteException e) {
220 | Log.w(TAG, "Cannot connect to keystore", e);
221 | return false;
222 | }
223 | }
224 |
225 | public boolean generate(String key, int uid, int flags) {
226 | try {
227 | return mBinder.generate(key, uid,
228 | flags) == NO_ERROR;
229 | } catch (RemoteException e) {
230 | Log.w(TAG, "Cannot connect to keystore", e);
231 | return false;
232 | }
233 | }
234 |
235 | public boolean importKey(String keyName, byte[] key, int uid, int flags) {
236 | try {
237 | return mBinder.import_key(keyName, key, uid, flags) == NO_ERROR;
238 | } catch (RemoteException e) {
239 | Log.w(TAG, "Cannot connect to keystore", e);
240 | return false;
241 | }
242 | }
243 |
244 | public byte[] getPubkey(String key) {
245 | try {
246 | return mBinder.get_pubkey(key);
247 | } catch (RemoteException e) {
248 | Log.w(TAG, "Cannot connect to keystore", e);
249 | return null;
250 | }
251 | }
252 |
253 | public boolean delKey(String key, int uid) {
254 | try {
255 | return mBinder.del_key(key, uid) == NO_ERROR;
256 | } catch (RemoteException e) {
257 | Log.w(TAG, "Cannot connect to keystore", e);
258 | return false;
259 | }
260 | }
261 |
262 | public boolean delKey(String key) {
263 | return delKey(key, UID_SELF);
264 | }
265 |
266 | public byte[] sign(String key, byte[] data) {
267 | try {
268 | return mBinder.sign(key, data);
269 | } catch (RemoteException e) {
270 | Log.w(TAG, "Cannot connect to keystore", e);
271 | return null;
272 | }
273 | }
274 |
275 | public boolean verify(String key, byte[] data, byte[] signature) {
276 | try {
277 | return mBinder.verify(key, data, signature) == NO_ERROR;
278 | } catch (RemoteException e) {
279 | Log.w(TAG, "Cannot connect to keystore", e);
280 | return false;
281 | }
282 | }
283 |
284 | public boolean grant(String key, int uid) {
285 | try {
286 | return mBinder.grant(key, uid) == NO_ERROR;
287 | } catch (RemoteException e) {
288 | Log.w(TAG, "Cannot connect to keystore", e);
289 | return false;
290 | }
291 | }
292 |
293 | public boolean ungrant(String key, int uid) {
294 | try {
295 | return mBinder.ungrant(key, uid) == NO_ERROR;
296 | } catch (RemoteException e) {
297 | Log.w(TAG, "Cannot connect to keystore", e);
298 | return false;
299 | }
300 | }
301 |
302 | /**
303 | * Returns the last modification time of the key in milliseconds since the
304 | * epoch. Will return -1L if the key could not be found or other error.
305 | */
306 | public long getmtime(String key) {
307 | try {
308 | final long millis = mBinder.getmtime(key);
309 | if (millis == -1L) {
310 | return -1L;
311 | }
312 |
313 | return millis * 1000L;
314 | } catch (RemoteException e) {
315 | Log.w(TAG, "Cannot connect to keystore", e);
316 | return -1L;
317 | }
318 | }
319 |
320 | public boolean duplicate(String srcKey, int srcUid, String destKey,
321 | int destUid) {
322 | try {
323 | return mBinder.duplicate(srcKey, srcUid, destKey, destUid) == NO_ERROR;
324 | } catch (RemoteException e) {
325 | Log.w(TAG, "Cannot connect to keystore", e);
326 | return false;
327 | }
328 | }
329 |
330 | public boolean isHardwareBacked() {
331 | try {
332 | return mBinder.is_hardware_backed() == NO_ERROR;
333 | } catch (RemoteException e) {
334 | Log.w(TAG, "Cannot connect to keystore", e);
335 | return false;
336 | }
337 | }
338 |
339 | public boolean clearUid(int uid) {
340 | try {
341 | return mBinder.clear_uid(uid) == NO_ERROR;
342 | } catch (RemoteException e) {
343 | Log.w(TAG, "Cannot connect to keystore", e);
344 | return false;
345 | }
346 | }
347 |
348 | public int getLastError() {
349 | return mError;
350 | }
351 | }
352 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/android/security/KeyStoreKk.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2009 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | //package android.security;
18 | package org.nick.androidkeystore.android.security;
19 |
20 | import java.lang.reflect.InvocationTargetException;
21 | import java.lang.reflect.Method;
22 | import java.util.Locale;
23 |
24 | import android.os.IBinder;
25 | import android.os.RemoteException;
26 | import android.security.IKeystoreService;
27 | import android.util.Log;
28 |
29 | /**
30 | * @hide This should not be made public in its present form because it
31 | * assumes that private and secret key bytes are available and would
32 | * preclude the use of hardware crypto.
33 | */
34 | public class KeyStoreKk extends KeyStore {
35 | private static final String TAG = "KeyStore";
36 |
37 | // ResponseCodes
38 | public static final int NO_ERROR = 1;
39 | public static final int LOCKED = 2;
40 | public static final int UNINITIALIZED = 3;
41 | public static final int SYSTEM_ERROR = 4;
42 | public static final int PROTOCOL_ERROR = 5;
43 | public static final int PERMISSION_DENIED = 6;
44 | public static final int KEY_NOT_FOUND = 7;
45 | public static final int VALUE_CORRUPTED = 8;
46 | public static final int UNDEFINED_ACTION = 9;
47 | public static final int WRONG_PASSWORD = 10;
48 |
49 | // Used for UID field to indicate the calling UID.
50 | public static final int UID_SELF = -1;
51 |
52 | // Flags for "put" "import" and "generate"
53 | public static final int FLAG_NONE = 0;
54 | public static final int FLAG_ENCRYPTED = 1;
55 |
56 | // States
57 | // public enum State { UNLOCKED, LOCKED, UNINITIALIZED };
58 |
59 | private int mError = NO_ERROR;
60 |
61 | private final IKeystoreService mBinder;
62 |
63 | private KeyStoreKk(IKeystoreService binder) {
64 | mBinder = binder;
65 | }
66 |
67 | public static KeyStoreKk getInstance() {
68 | // IKeystoreService keystore = IKeystoreService.Stub.asInterface(ServiceManager
69 | // .getService("android.security.keystore"));
70 | // return new KeyStore(keystore);
71 | try {
72 | Class> smClass = Class.forName("android.os.ServiceManager");
73 |
74 | Method getService = smClass.getMethod("getService", String.class);
75 | IBinder binder = (IBinder) getService.invoke(null,
76 | "android.security.keystore");
77 | IKeystoreService keystore = IKeystoreService.Stub
78 | .asInterface(binder);
79 | return new KeyStoreKk(keystore);
80 | } catch (ClassNotFoundException e) {
81 | throw new RuntimeException(e);
82 | } catch (NoSuchMethodException e) {
83 | throw new RuntimeException(e);
84 | } catch (IllegalArgumentException e) {
85 | throw new RuntimeException(e);
86 | } catch (IllegalAccessException e) {
87 | throw new RuntimeException(e);
88 | } catch (InvocationTargetException e) {
89 | throw new RuntimeException(e);
90 | }
91 | }
92 |
93 | static int getKeyTypeForAlgorithm(String keyType) throws IllegalArgumentException {
94 | if ("RSA".equalsIgnoreCase(keyType)) {
95 | return NativeCryptoConstants.EVP_PKEY_RSA;
96 | } else if ("DSA".equalsIgnoreCase(keyType)) {
97 | return NativeCryptoConstants.EVP_PKEY_DSA;
98 | } else if ("EC".equalsIgnoreCase(keyType)) {
99 | return NativeCryptoConstants.EVP_PKEY_EC;
100 | } else {
101 | throw new IllegalArgumentException("Unsupported key type: " + keyType);
102 | }
103 | }
104 |
105 | public State state() {
106 | final int ret;
107 | try {
108 | ret = mBinder.test();
109 | } catch (RemoteException e) {
110 | Log.w(TAG, "Cannot connect to keystore", e);
111 | throw new AssertionError(e);
112 | }
113 |
114 | switch (ret) {
115 | case NO_ERROR: return State.UNLOCKED;
116 | case LOCKED: return State.LOCKED;
117 | case UNINITIALIZED: return State.UNINITIALIZED;
118 | default: throw new AssertionError(mError);
119 | }
120 | }
121 |
122 | public boolean isUnlocked() {
123 | return state() == State.UNLOCKED;
124 | }
125 |
126 | public byte[] get(String key) {
127 | try {
128 | return mBinder.get(key);
129 | } catch (RemoteException e) {
130 | Log.w(TAG, "Cannot connect to keystore", e);
131 | return null;
132 | }
133 | }
134 |
135 | @Override
136 | public boolean put(String key, byte[] value) {
137 | return put(key, value, UID_SELF, FLAG_ENCRYPTED);
138 | }
139 |
140 | public boolean put(String key, byte[] value, int uid, int flags) {
141 | try {
142 | return mBinder.insert(key, value, uid, flags) == NO_ERROR;
143 | } catch (RemoteException e) {
144 | Log.w(TAG, "Cannot connect to keystore", e);
145 | return false;
146 | }
147 | }
148 |
149 | public boolean delete(String key, int uid) {
150 | try {
151 | return mBinder.del(key, uid) == NO_ERROR;
152 | } catch (RemoteException e) {
153 | Log.w(TAG, "Cannot connect to keystore", e);
154 | return false;
155 | }
156 | }
157 |
158 | public boolean delete(String key) {
159 | return delete(key, UID_SELF);
160 | }
161 |
162 | public boolean contains(String key, int uid) {
163 | try {
164 | return mBinder.exist(key, uid) == NO_ERROR;
165 | } catch (RemoteException e) {
166 | Log.w(TAG, "Cannot connect to keystore", e);
167 | return false;
168 | }
169 | }
170 |
171 | public boolean contains(String key) {
172 | return contains(key, UID_SELF);
173 | }
174 |
175 | public String[] saw(String prefix, int uid) {
176 | try {
177 | return mBinder.saw(prefix, uid);
178 | } catch (RemoteException e) {
179 | Log.w(TAG, "Cannot connect to keystore", e);
180 | return null;
181 | }
182 | }
183 |
184 | public String[] saw(String prefix) {
185 | return saw(prefix, UID_SELF);
186 | }
187 |
188 | public boolean reset() {
189 | try {
190 | return mBinder.reset() == NO_ERROR;
191 | } catch (RemoteException e) {
192 | Log.w(TAG, "Cannot connect to keystore", e);
193 | return false;
194 | }
195 | }
196 |
197 | public boolean password(String password) {
198 | try {
199 | return mBinder.password(password) == NO_ERROR;
200 | } catch (RemoteException e) {
201 | Log.w(TAG, "Cannot connect to keystore", e);
202 | return false;
203 | }
204 | }
205 |
206 | public boolean lock() {
207 | try {
208 | return mBinder.lock() == NO_ERROR;
209 | } catch (RemoteException e) {
210 | Log.w(TAG, "Cannot connect to keystore", e);
211 | return false;
212 | }
213 | }
214 |
215 | public boolean unlock(String password) {
216 | try {
217 | mError = mBinder.unlock(password);
218 | return mError == NO_ERROR;
219 | } catch (RemoteException e) {
220 | Log.w(TAG, "Cannot connect to keystore", e);
221 | return false;
222 | }
223 | }
224 |
225 | public boolean isEmpty() {
226 | try {
227 | return mBinder.zero() == KEY_NOT_FOUND;
228 | } catch (RemoteException e) {
229 | Log.w(TAG, "Cannot connect to keystore", e);
230 | return false;
231 | }
232 | }
233 |
234 | public boolean generate(String key, int uid, int keyType, int keySize, int flags,
235 | byte[][] args) {
236 | try {
237 | return mBinder.generate(key, uid, keyType, keySize, flags, args) == NO_ERROR;
238 | } catch (RemoteException e) {
239 | Log.w(TAG, "Cannot connect to keystore", e);
240 | return false;
241 | }
242 | }
243 |
244 | public boolean importKey(String keyName, byte[] key, int uid, int flags) {
245 | try {
246 | return mBinder.import_key(keyName, key, uid, flags) == NO_ERROR;
247 | } catch (RemoteException e) {
248 | Log.w(TAG, "Cannot connect to keystore", e);
249 | return false;
250 | }
251 | }
252 |
253 | public byte[] getPubkey(String key) {
254 | try {
255 | return mBinder.get_pubkey(key);
256 | } catch (RemoteException e) {
257 | Log.w(TAG, "Cannot connect to keystore", e);
258 | return null;
259 | }
260 | }
261 |
262 | public boolean delKey(String key, int uid) {
263 | try {
264 | return mBinder.del_key(key, uid) == NO_ERROR;
265 | } catch (RemoteException e) {
266 | Log.w(TAG, "Cannot connect to keystore", e);
267 | return false;
268 | }
269 | }
270 |
271 | public boolean delKey(String key) {
272 | return delKey(key, UID_SELF);
273 | }
274 |
275 | public byte[] sign(String key, byte[] data) {
276 | try {
277 | return mBinder.sign(key, data);
278 | } catch (RemoteException e) {
279 | Log.w(TAG, "Cannot connect to keystore", e);
280 | return null;
281 | }
282 | }
283 |
284 | public boolean verify(String key, byte[] data, byte[] signature) {
285 | try {
286 | return mBinder.verify(key, data, signature) == NO_ERROR;
287 | } catch (RemoteException e) {
288 | Log.w(TAG, "Cannot connect to keystore", e);
289 | return false;
290 | }
291 | }
292 |
293 | public boolean grant(String key, int uid) {
294 | try {
295 | return mBinder.grant(key, uid) == NO_ERROR;
296 | } catch (RemoteException e) {
297 | Log.w(TAG, "Cannot connect to keystore", e);
298 | return false;
299 | }
300 | }
301 |
302 | public boolean ungrant(String key, int uid) {
303 | try {
304 | return mBinder.ungrant(key, uid) == NO_ERROR;
305 | } catch (RemoteException e) {
306 | Log.w(TAG, "Cannot connect to keystore", e);
307 | return false;
308 | }
309 | }
310 |
311 | /**
312 | * Returns the last modification time of the key in milliseconds since the
313 | * epoch. Will return -1L if the key could not be found or other error.
314 | */
315 | public long getmtime(String key) {
316 | try {
317 | final long millis = mBinder.getmtime(key);
318 | if (millis == -1L) {
319 | return -1L;
320 | }
321 |
322 | return millis * 1000L;
323 | } catch (RemoteException e) {
324 | Log.w(TAG, "Cannot connect to keystore", e);
325 | return -1L;
326 | }
327 | }
328 |
329 | public boolean duplicate(String srcKey, int srcUid, String destKey, int destUid) {
330 | try {
331 | return mBinder.duplicate(srcKey, srcUid, destKey, destUid) == NO_ERROR;
332 | } catch (RemoteException e) {
333 | Log.w(TAG, "Cannot connect to keystore", e);
334 | return false;
335 | }
336 | }
337 |
338 | // TODO remove this when it's removed from Settings
339 | public boolean isHardwareBacked() {
340 | return isHardwareBacked("RSA");
341 | }
342 |
343 | public boolean isHardwareBacked(String keyType) {
344 | try {
345 | return mBinder.is_hardware_backed(keyType.toUpperCase(Locale.US)) == NO_ERROR;
346 | } catch (RemoteException e) {
347 | Log.w(TAG, "Cannot connect to keystore", e);
348 | return false;
349 | }
350 | }
351 |
352 | public boolean clearUid(int uid) {
353 | try {
354 | return mBinder.clear_uid(uid) == NO_ERROR;
355 | } catch (RemoteException e) {
356 | Log.w(TAG, "Cannot connect to keystore", e);
357 | return false;
358 | }
359 | }
360 |
361 | public int getLastError() {
362 | return mError;
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/src/org/nick/androidkeystore/android/security/NativeCryptoConstants.java:
--------------------------------------------------------------------------------
1 | package org.nick.androidkeystore.android.security;
2 |
3 | public class NativeCryptoConstants {
4 |
5 | public static final int EVP_PKEY_RSA = 6; // NID_rsaEcnryption
6 | public static final int EVP_PKEY_DSA = 116; // NID_dsa
7 | public static final int EVP_PKEY_DH = 28; // NID_dhKeyAgreement
8 | public static final int EVP_PKEY_EC = 408; // NID_X9_62_id_ecPublicKey
9 | public static final int EVP_PKEY_HMAC = 855; // NID_hmac
10 | public static final int EVP_PKEY_CMAC = 894; // NID_cmac
11 |
12 |
13 | private NativeCryptoConstants() {
14 | }
15 | }
16 |
--------------------------------------------------------------------------------