1+ package it .eng .knowage .tomcatpasswordencryption .helper ;
2+
3+ import org .jasypt .encryption .pbe .StandardPBEStringEncryptor ;
4+ import org .jasypt .encryption .pbe .config .SimpleStringPBEConfig ;
5+
6+ import java .io .IOException ;
7+ import java .nio .charset .StandardCharsets ;
8+ import java .nio .file .Files ;
9+ import java .nio .file .Path ;
10+
11+ public final class EncryptedPasswordUtils {
12+ private static final String ENCRYPTED_PREFIX = "#encr#" ;
13+
14+ private EncryptedPasswordUtils () {}
15+
16+ public static String decrypt (String value ) {
17+ if (value == null || value .isEmpty ()) return value ;
18+ if (!value .startsWith (ENCRYPTED_PREFIX )) {
19+ return value ;
20+ }
21+ String cipherText = value .substring (ENCRYPTED_PREFIX .length ());
22+ String password = resolveKey ();
23+ if (password == null || password .isEmpty ()) {
24+ throw new IllegalStateException ("""
25+ Missing decryption key. Provide it via system property knowage.enc.password, " +
26+ "environment variable KNOWAGE_ENC_PASSWORD, or a file at ${catalina.base}/conf/knowageTomcatEncryptedPasswordDatasource " +
27+ "or -Dknowage.enc.password.file=/secure/path
28+ """ );
29+ }
30+
31+ SimpleStringPBEConfig cfg = new SimpleStringPBEConfig ();
32+ cfg .setPassword (password );
33+ cfg .setPoolSize ("1" );
34+ cfg .setStringOutputType ("base64" );
35+
36+ StandardPBEStringEncryptor enc = new StandardPBEStringEncryptor ();
37+ enc .setConfig (cfg );
38+ return enc .decrypt (cipherText );
39+ }
40+
41+ public static String resolveKey () {
42+ // Prefer explicit file path via system property
43+ String fileProp = System .getProperty ("knowage.enc.password.file" );
44+ if (fileProp != null && !fileProp .isEmpty ()) {
45+ String fromFile = readFirstLineTrimmed (Path .of (fileProp ));
46+ if (fromFile != null && !fromFile .isEmpty ()) return fromFile ;
47+ }
48+
49+ // Default file under Tomcat conf: ${catalina.base}/conf/passwordEncryptionSecret
50+ String catalinaBase = System .getProperty ("catalina.base" );
51+ if (catalinaBase != null && !catalinaBase .isEmpty ()) {
52+ Path defaultPath = Path .of (catalinaBase , "conf" , "knowageTomcatEncryptedPasswordDatasource" );
53+ String fromFile = readFirstLineTrimmed (defaultPath );
54+ if (fromFile != null && !fromFile .isEmpty ()) return fromFile ;
55+ }
56+
57+ return null ;
58+ }
59+
60+ private static String readFirstLineTrimmed (Path path ) {
61+ try {
62+ if (Files .isRegularFile (path )) {
63+ for (String line : Files .readAllLines (path , StandardCharsets .UTF_8 )) {
64+ String trimmed = line .trim ();
65+ if (!trimmed .isEmpty ()) return trimmed ;
66+ }
67+ }
68+ } catch (IOException ignored ) {
69+ }
70+ return null ;
71+ }
72+
73+
74+ }
0 commit comments