66 */
77import in .erail .glue .annotation .StartService ;
88import io .reactivex .Single ;
9+ import io .vertx .core .eventbus .EventBusOptions ;
910import io .vertx .reactivex .core .Vertx ;
1011import java .security .InvalidAlgorithmParameterException ;
1112import java .security .InvalidKeyException ;
1213import java .security .NoSuchAlgorithmException ;
1314import java .security .SecureRandom ;
1415import java .util .Arrays ;
1516import java .util .Base64 ;
17+ import java .util .Optional ;
1618import java .util .concurrent .CompletableFuture ;
1719import java .util .concurrent .ExecutionException ;
1820import javax .crypto .BadPaddingException ;
@@ -36,20 +38,23 @@ public class SecurityTools {
3638 public void startup () {
3739
3840 setRandom (new SecureRandom ());
39-
40- if (!getVertx ().isClustered ()) {
41- mGlobalUniqueString .complete ("A" + mRandom .nextInt ());
42- return ;
41+
42+ if (getVertx ().isClustered ()) {
43+ byte [] key = generateKey ().get ();
44+ addValueToClusterMap ("key" , key )
45+ .subscribe ((k ) -> {
46+ String unique = Base64 .getEncoder ().encodeToString (Arrays .copyOfRange (k , 0 , 5 ));
47+ mGlobalUniqueString .complete (unique .replace ("=" , "" ));
48+ getLog ().info (() -> String .format ("GlobalUniqueString:[%s]" , unique ));
49+
50+ mKeySpec .complete (new SecretKeySpec (k , "AES" ));
51+ });
52+ } else {
53+ byte [] k = generateKey ().get ();
54+ String unique = Base64 .getEncoder ().encodeToString (Arrays .copyOfRange (k , 0 , 5 ));
55+ mGlobalUniqueString .complete (unique .replace ("=" , "" ));
56+ mKeySpec .complete (new SecretKeySpec (k , "AES" ));
4357 }
44-
45- generateKey ()
46- .flatMap (v -> addValueToClusterMap ("key" , v ))
47- .subscribe ((key ) -> {
48- mKeySpec .complete (new SecretKeySpec (key , "AES" ));
49- String unique = Base64 .getEncoder ().encodeToString (Arrays .copyOfRange (key , 0 , 5 ));
50- mGlobalUniqueString .complete (unique .replace ("=" , "" ));
51- getLog ().info (() -> String .format ("GlobalUniqueString:[%s]" , unique ));
52- });
5358 }
5459
5560 protected Single <byte []> addValueToClusterMap (String pKey , byte [] pValue ) {
@@ -60,15 +65,15 @@ protected Single<byte[]> addValueToClusterMap(String pKey, byte[] pValue) {
6065 .toSingle (pValue );
6166 }
6267
63- protected Single <byte []> generateKey () {
64- KeyGenerator keygen ;
68+ protected Optional <byte []> generateKey () {
6569 try {
66- keygen = KeyGenerator .getInstance ("AES" );
70+ KeyGenerator keygen = KeyGenerator .getInstance ("AES" );
71+ keygen .init (128 );
72+ return Optional .of (keygen .generateKey ().getEncoded ());
6773 } catch (NoSuchAlgorithmException ex ) {
68- return Single .error (ex );
74+ getLog () .error (ex );
6975 }
70- keygen .init (128 );
71- return Single .just (keygen .generateKey ().getEncoded ());
76+ return Optional .empty ();
7277 }
7378
7479 /**
0 commit comments