Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5673b2be202d570014c7604050c652c10d1c4245 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
 * Copyright (c) 2010-2021 BSI Business Systems Integration AG.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     BSI Business Systems Integration AG - initial API and implementation
 */
package org.eclipse.scout.rt.platform.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.Principal;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.security.auth.Subject;

import org.eclipse.scout.rt.platform.exception.ProcessingException;
import org.eclipse.scout.rt.platform.util.Assertions;
import org.eclipse.scout.rt.platform.util.Assertions.AssertionException;
import org.eclipse.scout.rt.platform.util.Base64Utility;
import org.eclipse.scout.rt.platform.util.HexUtility;
import org.eclipse.scout.rt.platform.util.LazyValue;
import org.eclipse.scout.rt.platform.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utility class for encryption & decryption, hashing and creation of random numbers, message authentication codes and
 * digital signatures.<br>
 * The {@link Base64Utility} or {@link HexUtility} can be used to encode the bytes returned by this class.
 *
 * @since 5.1
 * @see Base64Utility
 * @see HexUtility
 * @see ISecurityProvider
 */
public final class SecurityUtility {
  private static final Logger LOG = LoggerFactory.getLogger(SecurityUtility.class);

  /**
   * Number of random bytes to be created by default.
   */
  private static final int DEFAULT_RANDOM_SIZE = 32;

  private static final LazyValue<ISecurityProvider> SECURITY_PROVIDER = new LazyValue<>(ISecurityProvider.class);

  private SecurityUtility() {
    // no instances of this class
  }

  /**
   * See {@link ISecurityProvider#encrypt(InputStream, OutputStream, EncryptionKey)}
   */
  public static void encrypt(InputStream clearTextData, OutputStream encryptedData, EncryptionKey key) {
    SECURITY_PROVIDER.get().encrypt(clearTextData, encryptedData, key);
  }

  /**
   * See {@link ISecurityProvider#decrypt(InputStream, OutputStream, EncryptionKey)}
   */
  public static void decrypt(InputStream encryptedData, OutputStream clearTextData, EncryptionKey key) {
    SECURITY_PROVIDER.get().decrypt(encryptedData, clearTextData, key);
  }

  /**
   * See {@link ISecurityProvider#createEncryptionKey(char[], byte[], int)}
   */
  public static EncryptionKey createEncryptionKey(char[] password, byte[] salt, int keyLen) {
    return SECURITY_PROVIDER.get().createEncryptionKey(password, salt, keyLen);
  }

  /**
   * Encrypts the given bytes using the given {@link EncryptionKey}.<br>
   * Use {@link #createEncryptionKey(char[], byte[], int)} to create a key instance.
   *
   * @param clearTextData
   *          The clear text data. Must not be {@code null}.
   * @param key
   *          The {@link EncryptionKey} to use. Must not be {@code null}.
   * @return The encrypted bytes
   * @throws AssertionException
   *           on invalid input.
   * @throws ProcessingException
   *           if there is an error during encryption.
   */
  public static byte[] encrypt(byte[] clearTextData, EncryptionKey key) {
    return doCrypt(clearTextData, key, true);
  }

  /**
   * Decrypts the given bytes using the given {@link EncryptionKey}.<br>
   * Use {@link #createEncryptionKey(char[], byte[], int)} to create a key instance.
   *
   * @param encryptedData
   *          The encrypted bytes. Must not be {@code null}.
   * @param key
   *          The {@link EncryptionKey} to use. Must not be {@code null}.
   * @return The clear text data.
   * @throws AssertionException
   *           on invalid input
   * @throws ProcessingException
   *           if there is an error during decryption.
   */
  public static byte[] decrypt(byte[] encryptedData, EncryptionKey key) {
    return doCrypt(encryptedData, key, false);
  }

  /**
   * Encrypts the given clear text bytes using the given password and salt.
   *
   * @param clearTextData
   *          The clear text data. Must not be {@code null}.
   * @param password
   *          The password to use to create the key. Must not be {@code null} or empty.
   * @param salt
   *          The salt to use for the key. Must not be {@code null} or empty. It is important to create a separate
   *          random salt for each key! Salts may not be shared by several keys. Use {@link #createRandomBytes(int)} to
   *          generate a new salt. It is safe to store the salt in clear text alongside the encrypted data.
   * @param keyLen
   *          The length of the key (in bits). Must be one of 128, 192 or 256.
   * @return The encrypted bytes.
   * @throws AssertionException
   *           on invalid input
   * @throws ProcessingException
   *           if there is an error during encryption.
   */
  public static byte[] encrypt(byte[] clearTextData, char[] password, byte[] salt, int keyLen) {
    return doCrypt(clearTextData, password, salt, keyLen, true);
  }

  /**
   * @param encryptedData
   *          The encrypted bytes. Must not be {@code null}.
   * @param password
   *          The password to use to create the key. Must not be {@code null} or empty.
   * @param salt
   *          The salt to use for the key. Must not be {@code null} or empty. It is important to create a separate
   *          random salt for each key! Salts may not be shared by several keys. Use {@link #createRandomBytes(int)} to
   *          generate a new salt. It is safe to store the salt in clear text alongside the encrypted data.
   * @param keyLen
   *          The length of the key (in bits). Must be one of 128, 192 or 256.
   * @return The clear text bytes.
   * @throws AssertionException
   *           on invalid input
   * @throws ProcessingException
   *           if there is an error during decryption.
   */
  public static byte[] decrypt(byte[] encryptedData, char[] password, byte[] salt, int keyLen) {
    return doCrypt(encryptedData, password, salt, keyLen, false);
  }

  static byte[] doCrypt(byte[] data, char[] password, byte[] salt, int keyLen, boolean encrypt) {
    EncryptionKey key = createEncryptionKey(password, salt, keyLen);
    return doCrypt(data, key, encrypt);
  }

  static byte[] doCrypt(byte[] data, EncryptionKey key, boolean encrypt) {
    Assertions.assertNotNull(data, "no data provided");

    // no need to close ByteArray-Streams
    ByteArrayInputStream input = new ByteArrayInputStream(data);
    int expectedOutSize = input.available();
    int aesBlockSize = 16;
    if (encrypt) {
      expectedOutSize = ((expectedOutSize / aesBlockSize) + 2) * aesBlockSize;
    }
    else {
      expectedOutSize -= 8;
    }
    ByteArrayOutputStream result = new ByteArrayOutputStream(expectedOutSize);
    if (encrypt) {
      encrypt(input, result, key);
    }
    else {
      decrypt(input, result, key);
    }
    return result.toByteArray();
  }

  /**
   * See {@link ISecurityProvider#createSecureRandomBytes(int)}
   */
  public static byte[] createRandomBytes(int numBytes) {
    return SECURITY_PROVIDER.get().createSecureRandomBytes(numBytes);
  }

  /**
   * Generates 32 random bytes.
   *
   * @return the created random bytes.
   * @throws ProcessingException
   *           If the current platform does not support the random number generation algorithm.
   * @see ISecurityProvider#createSecureRandomBytes(int)
   */
  public static byte[] createRandomBytes() {
    return createRandomBytes(DEFAULT_RANDOM_SIZE);
  }

  /**
   * See {@link ISecurityProvider#createSecureRandom()}
   */
  public static SecureRandom createSecureRandom() {
    return SECURITY_PROVIDER.get().createSecureRandom();
  }

  /**
   * @see ISecurityProvider#createPasswordHash(char[], byte[])
   */
  public static byte[] hashPassword(char[] password, byte[] salt) {
    return SECURITY_PROVIDER.get().createPasswordHash(password, salt);
  }

  /**
   * It is recommended to use {@link #hashPassword(char[], byte[])} without iteration count.
   *
   * @see ISecurityProvider#createPasswordHash(char[], byte[], int)
   */
  public static byte[] hashPassword(char[] password, byte[] salt, int iterations) {
    return SECURITY_PROVIDER.get().createPasswordHash(password, salt, iterations);
  }

  /**
   * This method is recommended in combination with {@link #hashPassword(char[], byte[])} where the iteration count is
   * omitted. This has the advantage that the check of the password hash is independent of the creation of the hash. In
   * case the iteration count is increased yearly, this method checks if the hash is valid
   *
   * @return true if calculated password has with {@link #hashPassword(char[], byte[], int)} matches the expected hash.
   * @since 11.0
   */
  public static boolean verifyPasswordHash(char[] password, byte[] salt, byte[] expectedHash) {
    return SECURITY_PROVIDER.get().verifyPasswordHash(password, salt, expectedHash);
  }

  /**
   * Creates a hash for the given data using the given salt.<br>
   * <br>
   * <b>Important:</b> For hashing of passwords use {@link #hashPassword(char[], byte[], int)}!
   *
   * @param data
   *          The data to hash. Must not be {@code null}.
   * @param salt
   *          The salt to use. Use {@link #createRandomBytes(int)} to generate a random salt per instance.
   * @return the hash
   * @throws ProcessingException
   *           If there is an error creating the hash
   * @throws AssertionException
   *           If data is {@code null}.
   * @see ISecurityProvider#createHash(InputStream, byte[], int)
   * @see ISecurityProvider#createPasswordHash(char[], byte[], int)
   */
  public static byte[] hash(byte[] data, byte[] salt) {
    Assertions.assertNotNull(data, "no data provided");
    return hash(new ByteArrayInputStream(data), salt);
  }

  /**
   * See {@link ISecurityProvider#createHash(InputStream, byte[], int)}
   */
  public static byte[] hash(InputStream data, byte[] salt) {
    return SECURITY_PROVIDER.get().createHash(data, salt, 3557 /* number of default cycles for backwards compatibility */);
  }

  /**
   * See {@link ISecurityProvider#createKeyPair()}
   */
  public static KeyPairBytes generateKeyPair() {
    return SECURITY_PROVIDER.get().createKeyPair();
  }

  /**
   * See {@link ISecurityProvider#createSignature(byte[], InputStream)}
   */
  public static byte[] createSignature(byte[] privateKey, InputStream data) {
    return SECURITY_PROVIDER.get().createSignature(privateKey, data);
  }

  /**
   * Creates a signature for the given data using the given private key.<br>
   * Compatible keys can be generated using {@link #generateKeyPair()}.
   *
   * @param privateKey
   *          The private key bytes.
   * @param data
   *          The data for which the signature should be created.
   * @return The signature bytes.
   * @throws ProcessingException
   *           When there is an error creating the signature.
   * @throws AssertionException
   *           if the private key or data is {@code null}.
   * @see ISecurityProvider#createSignature(byte[], InputStream)
   */
  public static byte[] createSignature(byte[] privateKey, byte[] data) {
    Assertions.assertNotNull(data, "no data provided");
    return createSignature(privateKey, new ByteArrayInputStream(data));
  }

  /**
   * See {@link ISecurityProvider#verifySignature(byte[], InputStream, byte[])}
   */
  public static boolean verifySignature(byte[] publicKey, InputStream data, byte[] signatureToVerify) {
    return SECURITY_PROVIDER.get().verifySignature(publicKey, data, signatureToVerify);
  }

  /**
   * Verifies the given signature for the given data and public key.<br>
   * Compatible public keys can be generated using {@link #generateKeyPair()}.
   *
   * @param publicKey
   *          The public key bytes.
   * @param data
   *          The data for which the signature should be validated. Must not be {@code null}
   * @param signatureToVerify
   *          The signature that should be verified against.
   * @return {@code true} if the given signature is valid for the given data and public key. {@code false} otherwise.
   * @throws ProcessingException
   *           If there is an error validating the signature.
   * @throws AssertionException
   *           if one of the arguments is {@code null}.
   * @see ISecurityProvider#verifySignature(byte[], InputStream, byte[])
   */
  public static boolean verifySignature(byte[] publicKey, byte[] data, byte[] signatureToVerify) {
    Assertions.assertNotNull(data, "no data provided");
    return verifySignature(publicKey, new ByteArrayInputStream(data), signatureToVerify);
  }

  /**
   * See {@link ISecurityProvider#createMac(byte[], InputStream)}
   */
  public static byte[] createMac(byte[] password, InputStream data) {
    return SECURITY_PROVIDER.get().createMac(password, data);
  }

  /**
   * Create a Message Authentication Code (MAC) for the given data and password.
   *
   * @param password
   *          The password to create the authentication code.
   * @param data
   *          The data for which the code should be created. Must not be {@code null}.
   * @return The created authentication code.
   * @throws ProcessingException
   *           if there is an error creating the MAC
   * @throws AssertionException
   *           if the password or data is {@code null}.
   * @see ISecurityProvider#createMac(byte[], InputStream)
   */
  public static byte[] createMac(byte[] password, byte[] data) {
    Assertions.assertNotNull(data, "no data provided");
    return createMac(password, new ByteArrayInputStream(data));
  }

  /**
   * @return the principal names of the given {@link Subject}, or {@code null} if the given {@link Subject} is
   *         {@code null}. Multiple principal names are separated by comma.
   */
  public static String getPrincipalNames(Subject subject) {
    if (subject == null) {
      return null;
    }

    Set<Principal> principals = subject.getPrincipals();
    final List<String> principalNames = new ArrayList<>(principals.size());
    for (final Principal principal : principals) {
      principalNames.add(principal.getName());
    }
    return StringUtility.join(", ", principalNames);
  }

  /**
   * Auto-generate a self-signed X509 certificate with public key and private key in a JKS keystore. If the keystore
   * file already exists, then it is re-used and not created.
   *
   * @param keyStorePath
   *          must be an URI starting with 'file:' for example file:/dev/data/... or file:/c:/dev/data/...
   * @see #createSelfSignedCertificate(String, String, String, String, int, int, OutputStream)
   * @since 10.0
   */
  public static void autoCreateSelfSignedCertificate(String keyStorePath, String storePass, String keyPass, String certificateAlias, String x500Name) {
    if (x500Name != null) {
      if (!keyStorePath.startsWith("file:")) {
        throw new ProcessingException("When calling autoCreateSelfSignedCertificate then the keyStorePath ('{}') must be a 'file:' URL", keyStorePath);
      }
      try {
        File f = new File(new URI(keyStorePath).getSchemeSpecificPart());
        if (!f.exists()) {
          LOG.info("Creating new self-signed certificate '{}' with X500 name '{}'", certificateAlias, x500Name);
          try (FileOutputStream jks = new FileOutputStream(f)) {
            createSelfSignedCertificate(certificateAlias, x500Name, storePass, keyPass, 4096, 365, jks);
          }
        }
      }
      catch (IOException | URISyntaxException e) {
        throw new ProcessingException("Create self-signed certificate '{}' with X500 name '{}' in {}", certificateAlias, x500Name, keyStorePath, e);
      }
    }
  }

  /**
   * Create a self-signed X509 certificate with public key and private key in a JKS keystore.
   * <p>
   * Similar to: openssl req -nodes -newkey rsa:4096 -days 3650 -x509 -keyout cert_private.key -out cert_public.pem
   *
   * @param certificateAlias
   *          is the alias used in the keystore for accessing the certificate, this is not the certificate name (DN)
   * @param x500Name
   *          or Subject DN or Issuer DN for example "CN=host.domain.com,C=CH,S=ZH,L=Zurich,O=My Company",
   *
   *          <pre>
  X.500 name format is
  CN: CommonName: host.domain.com
  C: CountryName: CH
  S: StateOrProvinceName: ZH
  L: Locality: Zurich
  O: Organization: My Company
  OU: OrganizationalUnit:
   *          </pre>
   *
   * @param storePass
   *          keystore password
   * @param keyPass
   *          private key password
   * @param keyBits
   *          typically 4096
   * @param validDays
   *          typically 365 days
   * @param out
   *          where to write the generated keystore to
   * @since 10.0
   */
  public static void createSelfSignedCertificate(
      String certificateAlias,
      String x500Name,
      String storePass,
      String keyPass,
      int keyBits,
      int validDays,
      OutputStream out) {
    SECURITY_PROVIDER.get().createSelfSignedCertificate(certificateAlias, x500Name, storePass, keyPass, keyBits, validDays, out);
  }

  /**
   * @param keyStorePath
   *          url
   * @param storePass
   *          keystore password
   * @param keyPass
   *          private key password. Optional.
   * @see #keyStoreToHumanReadableText(InputStream, String, String)
   * @since 10.0
   */
  public static String keyStoreToHumanReadableText(String keyStorePath, String storePass, String keyPass) {
    try (InputStream in = new URL(keyStorePath).openStream()) {
      return keyStoreToHumanReadableText(in, storePass, keyPass);
    }
    catch (IOException | RuntimeException e) {
      return "Error: " + e;
    }
  }

  /**
   * @param keyStoreInput
   *          stream
   * @param storePass
   *          keystore password
   * @param keyPass
   *          private key password. Optional.
   * @return human readable text of the keystore content
   * @since 10.0
   */
  public static String keyStoreToHumanReadableText(InputStream keyStoreInput, String storePass, String keyPass) {
    return SECURITY_PROVIDER.get().keyStoreToHumanReadableText(keyStoreInput, storePass, keyPass);
  }

  /**
   * Generates a new base64 encoded key pair and prints it on standard out.
   */
  public static void main(String[] args) {
    KeyPairBytes keyPair = generateKeyPair();
    System.out.format("base64 encoded key pair:%n  private key: %s%n  public key:  %s%n",
        Base64Utility.encode(keyPair.getPrivateKey()),
        Base64Utility.encode(keyPair.getPublicKey()));
  }
}

Back to the top