35
35
import java .io .FileOutputStream ;
36
36
import java .io .InputStream ;
37
37
import java .util .ArrayList ;
38
+ import java .util .Arrays ;
38
39
import java .util .Base64 ;
39
40
import java .util .Collection ;
40
41
import java .util .Collections ;
@@ -443,7 +444,28 @@ public static String encodePassword(String value) {
443
444
}
444
445
445
446
/**
446
- * Decodes given string using the Base64 enconding.
447
+ * Encodes given char[] using the Base64 encoding. The original parameter value is overwritten.
448
+ *
449
+ * @param value char[] to be encoded.
450
+ * @return encoded char[].
451
+ *
452
+ * @since VisualVM 1.4.3
453
+ */
454
+ public static char [] encodePassword (char [] value ) {
455
+ byte [] bytes = charsToBytes (value );
456
+ Arrays .fill (value , (char )0 );
457
+
458
+ byte [] bytes2 = Base64 .getEncoder ().encode (bytes );
459
+ Arrays .fill (bytes , (byte )0 );
460
+
461
+ char [] chars = bytesToChars (bytes2 );
462
+ Arrays .fill (bytes2 , (byte )0 );
463
+
464
+ return chars ;
465
+ }
466
+
467
+ /**
468
+ * Decodes given string using the Base64 encoding.
447
469
*
448
470
* @param value String to be decoded.
449
471
* @return decoded String.
@@ -452,6 +474,27 @@ public static String decodePassword(String value) {
452
474
return new String (Base64 .getDecoder ().decode (value ));
453
475
}
454
476
477
+ /**
478
+ * Decodes given char[] using the Base64 encoding. The original parameter value is overwritten.
479
+ *
480
+ * @param value char[] to be decoded.
481
+ * @return decoded char[].
482
+ *
483
+ * @since VisualVM 1.4.3
484
+ */
485
+ public static char [] decodePassword (char [] value ) {
486
+ byte [] bytes = charsToBytes (value );
487
+ Arrays .fill (value , (char )0 );
488
+
489
+ byte [] bytes2 = Base64 .getDecoder ().decode (bytes );
490
+ Arrays .fill (bytes , (byte )0 );
491
+
492
+ char [] chars = bytesToChars (bytes2 );
493
+ Arrays .fill (bytes2 , (byte )0 );
494
+
495
+ return chars ;
496
+ }
497
+
455
498
/**
456
499
* Encodes given image to String using the Base64 encoding.
457
500
* This is primarily intended to store small images (icons)
@@ -499,4 +542,23 @@ private static byte[] imageToBytes(Image image, String format) {
499
542
return outputStream .toByteArray ();
500
543
}
501
544
545
+ private static byte [] charsToBytes (char [] chars ) {
546
+ byte [] bytes = new byte [chars .length * 2 ];
547
+ for (int i = 0 ; i < chars .length ; i ++) {
548
+ bytes [i * 2 ] = (byte )((chars [i ] & 0xff00 ) >> 8 );
549
+ bytes [i * 2 + 1 ] = (byte )(chars [i ] & 0x00ff );
550
+ }
551
+ return bytes ;
552
+ }
553
+
554
+ private static char [] bytesToChars (byte [] bytes ) {
555
+ char [] chars = new char [bytes .length / 2 ];
556
+ for (int i = 0 ; i < chars .length ; i ++) {
557
+ char ch = (char )(((bytes [i * 2 ] & 0x00ff ) << 8 ) +
558
+ (bytes [i * 2 + 1 ] & 0x00ff ));
559
+ chars [i ] = ch ;
560
+ }
561
+ return chars ;
562
+ }
563
+
502
564
}
0 commit comments