· 7 years ago · Sep 16, 2018, 08:48 AM
1public static void main(String[] args) throws WamsExceptionWithIds
2 {
3 FileSaver fileSaver = new FileSaver(null, null); // LATER geht unter Linux nicht, da Benutzer-Namen fehlen
4 String path = PropertyPlaceholderConfigurer.getPropertyString(WAMSProps.NOTESID_KEYFILE_DIRECTORY);
5 NotesIdCrypterImpl_RSA2048 crypt = new NotesIdCrypterImpl_RSA2048(fileSaver, path);
6 KeyPair keyPair = crypt.generateKeyForNotesId(null);
7
8 crypt.saveKeyForNotesIdId(keyPair, 6);
9 keyPair = crypt.getOrGenerateKeyForNotesId(6);
10 File uncrypted = new File("C:\\eclipse\\testFile.exe");
11 File deCrypted = new File("C:\\eclipse\\testDectyped.exe");
12 // File enrypted = new File("C:\\eclipse\\ubuEncrypt.iso");
13
14 byte[] uncryptedBytes = new byte[(int) uncrypted.length()];
15 try
16 {
17 InputStream is = new FileInputStream(uncrypted);
18 is.read(uncryptedBytes);
19 }
20 catch (FileNotFoundException e)
21 {
22 // für Testzwecke
23 e.printStackTrace();
24 }
25 catch (IOException e)
26 {
27 // für Testzwecke
28 e.printStackTrace();
29 }
30 byte[] encrypted = crypt.encryptBytes(uncryptedBytes, keyPair, null);
31
32 byte[] decrypted = crypt.decryptBytes(encrypted, keyPair, null);
33
34 if (Util.isEmpty(decrypted))
35 {
36 System.out.println("DecryptedBytes leer");
37 return;
38 }
39
40 try
41 {
42 OutputStream os = new FileOutputStream(deCrypted);
43 os.write(decrypted);
44 }
45 catch (FileNotFoundException e)
46 {
47 // für Testzwecke
48 e.printStackTrace();
49 }
50 catch (IOException e)
51 {
52 // für Testzwecke
53 e.printStackTrace();
54 }
55 }
56
57 @Override
58 public byte[] encryptBytes(byte[] bytes, Object keyFile, Integer notesIdIdForLog) throws WamsExceptionWithIds
59 {
60 if (Util.isEmpty(bytes) || Util.isEmpty(keyFile))
61 throw new IllegalArgumentException("Given notesID or keyfile is not valid");
62
63 PublicKey publicKey = null;
64
65 if (keyFile instanceof PublicKey)
66 publicKey = (PublicKey) keyFile;
67 else if (keyFile instanceof KeyPair)
68 publicKey = ((KeyPair) keyFile).getPublic();
69 else
70 throw new IllegalArgumentException("Given keyObject is not valid");
71
72 byte[] data = null;
73
74 try
75 {
76 // Create cipher object
77 KeyGenerator keygen = KeyGenerator.getInstance("AES");
78 SecureRandom random = new SecureRandom();
79 keygen.init(random); // Initialize with random data
80 SecretKey key = keygen.generateKey();
81
82 ByteArrayOutputStream out = new ByteArrayOutputStream();
83 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
84 cipher.init(Cipher.WRAP_MODE, publicKey);
85 byte[] wrappedKey = cipher.wrap(key);
86 out.write(wrappedKey.length);
87 out.write(wrappedKey);
88
89 InputStream in = new ByteArrayInputStream(bytes);
90 cipher = Cipher.getInstance("AES");
91 cipher.init(Cipher.ENCRYPT_MODE, key);
92 crypt(in, out, cipher, notesIdIdForLog, "en");
93 data = out.toByteArray();
94 in.close();
95 out.close();
96 }
97 catch (IOException e)
98 {
99 throw internalError(ErrorCodes.CRYPTER_CRYPT_IO, "Could not encrypt bytes", e);
100 }
101 catch (GeneralSecurityException e)
102 {
103 throw internalError(CommonErrorCodes.INTERNAL_ERROR, "Could not encrypt cause securityexception", e);
104 }
105
106 return data;
107 }
108
109 @Override
110 public byte[] decryptBytes(byte[] bytes, Object key, Integer notesIdIdForLog) throws WamsExceptionWithIds
111 {
112 if (Util.isEmpty(bytes) || Util.isEmpty(key))
113 throw new IllegalArgumentException("Given notesID or keyfile is not valid");
114
115 PrivateKey privateKey;
116 if (key instanceof PrivateKey)
117 privateKey = (PrivateKey) key;
118 else if (key instanceof KeyPair)
119 privateKey = ((KeyPair) key).getPrivate();
120 else
121 throw new IllegalArgumentException("Given keyObject is not valid");
122
123 try
124 {
125 ByteArrayInputStream in = new ByteArrayInputStream(bytes);
126 int length = in.read();
127 byte[] wrappedKey = new byte[length];
128 int readBytes = in.read(wrappedKey, 0, length);
129 if (readBytes != length)
130 throw internalError(ErrorCodes.CRYPTER_CRYPT_IO, "read " + readBytes + " bytes, but should read " + length + ".");
131
132 ByteArrayOutputStream out = new ByteArrayOutputStream();
133 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
134 cipher.init(Cipher.UNWRAP_MODE, privateKey);
135 Key publicKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
136
137 cipher = Cipher.getInstance("AES");
138 cipher.init(Cipher.DECRYPT_MODE, publicKey);
139
140 crypt(in, out, cipher, notesIdIdForLog, "de");
141 byte[] data = out.toByteArray();
142 in.close();
143 out.close();
144 return data;
145 }
146 catch (IOException e)
147 {
148 throw internalError(ErrorCodes.CRYPTER_CRYPT_IO, "Could not decrypt bytes.", e);
149 }
150 catch (GeneralSecurityException e)
151 {
152 throw internalError(CommonErrorCodes.INTERNAL_ERROR, "Could not encrypt cause securityexception", e);
153 }
154 }
155
156 /**
157 * Metadata can be NULL. This Method will create a new KeyPair. If Metadata is given and Metadata has a ID, this method will
158 * save the KeyPair on HDD
159 * @return KeyPair
160 * @throws WamsExceptionWithIds
161 */
162 @SuppressWarnings("unchecked")
163 @Override
164 public <T> T generateKeyForNotesId(NotesId notesId) throws WamsExceptionWithIds
165 {
166 log.log(LogLevel.TRACE, "Generating new RSA key", WamsUtil.getIdOrNull(notesId));
167 KeyPairGenerator pairGen;
168 try
169 {
170 pairGen = KeyPairGenerator.getInstance("RSA");
171 }
172 catch (GeneralSecurityException e)
173 {
174 throw internalError(CommonErrorCodes.INTERNAL_ERROR, "Could not generate keyfile", e);
175 }
176 SecureRandom random = new SecureRandom();
177 pairGen.initialize(KEYSIZE, random);
178 KeyPair keyPair = pairGen.generateKeyPair();
179 if (notesId != null && notesId.getIdOrNull() != null)
180 this.saveKeyForNotesId(keyPair, notesId);
181 return (T) keyPair;
182 }
183
184 /**
185 * @param notesId
186 * die {@link NotesId#getIdOrNull() ID} muss gesetzt sein
187 */
188 @Override
189 public void saveKeyForNotesId(Object key, NotesId notesId) throws WamsExceptionWithIds
190 {
191 if (Util.isEmpty(key))
192 throw new IllegalArgumentException("The key to use is empty");
193 if (Util.isEmpty(notesId))
194 throw new IllegalArgumentException("The notesId is null");
195 if (notesId.getIdOrNull() == null)
196 throw new IllegalArgumentException("the id of the notes id must be given");
197 super.saveKeyForNotesIdId(key, notesId.getId());
198 }
199
200 /**
201 *
202 * @param in
203 * @param out
204 * @param cipher
205 * @param notesIdIdForLog
206 * @param deOrEnForLog
207 * "de" or "en" als Prefix vor "crypting"
208 * @throws IOException
209 * @throws ShortBufferException
210 * @throws IllegalBlockSizeException
211 * @throws BadPaddingException
212 */
213 private void crypt(InputStream in, OutputStream out, Cipher cipher, Integer notesIdIdForLog, String deOrEnForLog)
214 throws IOException, ShortBufferException, IllegalBlockSizeException, BadPaddingException
215 {
216 boolean isTraceEnabled = log.isEnabled(LogLevel.TRACE);
217 if (isTraceEnabled)
218 log.log(LogLevel.TRACE, "Start " + deOrEnForLog + "-crypting", notesIdIdForLog);
219 int blockSize = cipher.getBlockSize();
220 int outputSize = cipher.getOutputSize(blockSize);
221 byte[] input = new byte[blockSize];
222 byte[] output = new byte[outputSize];
223 int inLength = 0;
224 boolean finished = false;
225
226 while (!finished)
227 {
228 inLength = in.read(input);
229
230 if (inLength == blockSize)
231 {
232 int outLength = cipher.update(input, 0, blockSize, output);
233 out.write(output, 0, outLength);
234 }
235 else
236 {
237 finished = true;
238 }
239 }
240
241 if (inLength > 0)
242 output = cipher.doFinal(input, 0, inLength);
243 else
244 output = cipher.doFinal();
245
246 out.write(output);
247 if (isTraceEnabled)
248 log.log(LogLevel.TRACE, "Finished " + deOrEnForLog + "-crypting", notesIdIdForLog);
249 }