00001
package com.quadcap.crypto;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
import java.util.Random;
00042
00043
00044
00045
00046
00047
00048 public class KeyFactory {
00049
00050
00051
00052
00053 public static SymmetricKey createSymmetricKey(Random r) {
00054
SymmetricKey k =
new Tea();
00055 k.
init(r);
00056
return k;
00057 }
00058
00059
00060
00061
00062
00063 public static SymmetricKey createSymmetricKey(String passphrase) {
00064
return createSymmetricKey(
"aes:128", passphrase);
00065 }
00066
00067
00068
00069
00070 public static byte[]
bytesFromPassphrase(
int len, String passphrase) {
00071 byte[] key =
new byte[len];
00072
long seed = 13 * passphrase.length();
00073
for (
int i = 0; i < key.length; i++) {
00074
int c = passphrase.charAt(i % passphrase.length());
00075 seed += (c << 18) ^ c;
00076 seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
00077 key[i] = (byte)((seed >> 5) & 0xff);
00078 }
00079
return key;
00080 }
00081
00082
00083
00084
00085
00086
00087 public static SymmetricKey createSymmetricKey(String algo,
00088 String passphrase) {
00089
SymmetricKey k = null;
00090
00091 algo = algo.toLowerCase();
00092
if (algo.startsWith(
"aes")) {
00093
int len = 16;
00094
int idx = algo.indexOf(
':');
00095
if (idx > 0) {
00096 len = Integer.parseInt(algo.substring(idx+1)) / 8;
00097 }
00098
Rijndael rk =
new Rijndael();
00099 rk.
init(bytesFromPassphrase(len, passphrase));
00100 k = rk;
00101 }
else if (algo.startsWith(
"tea:256")) {
00102
Tea256 tk =
new Tea256();
00103 tk.
init(bytesFromPassphrase(256, passphrase));
00104 k = tk;
00105 }
else if (algo.startsWith(
"tea:128")) {
00106
Tea tk =
new Tea();
00107 tk.
init(bytesFromPassphrase(128, passphrase));
00108 k = tk;
00109 }
00110
return k;
00111 }
00112
00113
00114
00115
00116 public static PrivateKey createPrivateKey(Random r, String alg,
00117 String name) {
00118
RSAPrivateKey k =
new RSAPrivateKey();
00119 k.
init(name, 1024, r);
00120
return k;
00121 }
00122
00123
00124
00125
00126 public static SymmetricKey readSymmetricKey(String s) {
00127
Tea t =
new Tea();
00128 t.
init(s);
00129
return t;
00130 }
00131
00132
00133
00134
00135 public static PublicKey readPublicKey(String s) {
00136
RSAPublicKey k =
new RSAPublicKey();
00137 k.
init(s);
00138
return k;
00139 }
00140
00141
00142
00143
00144 public static PrivateKey readPrivateKey(String s) {
00145
RSAPrivateKey k =
new RSAPrivateKey();
00146 k.
init(s);
00147
return k;
00148 }
00149
00150
00151
00152
00153 public static Digest createDigest(String alg) {
00154
return new SHA1Digest();
00155 }
00156
00157 public static Random
createRandom(String seed) {
00158 Random r =
new java.util.Random();
00159 r.setSeed(System.currentTimeMillis() * 1003 + seed.hashCode());
00160
return r;
00161 }
00162
00163 }