• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 38940517578

16 Oct 2026 05:32PM UTC coverage: 66.447% (+0.01%) from 66.433%
38940517578

push

github

ibacher
Correct link to CI

25988 of 39111 relevant lines covered (66.45%)

0.66 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

73.49
/api/src/main/java/org/openmrs/util/Security.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.util;
11

12
import java.nio.charset.StandardCharsets;
13
import java.security.GeneralSecurityException;
14
import java.security.MessageDigest;
15
import java.security.NoSuchAlgorithmException;
16
import java.security.SecureRandom;
17
import java.util.Base64;
18
import java.util.HashMap;
19
import java.util.Map;
20
import java.util.Random;
21

22
import javax.crypto.Cipher;
23
import javax.crypto.KeyGenerator;
24
import javax.crypto.SecretKey;
25
import javax.crypto.spec.IvParameterSpec;
26
import javax.crypto.spec.SecretKeySpec;
27

28
import org.openmrs.api.APIException;
29
import org.openmrs.api.context.Context;
30
import org.openmrs.api.context.ServiceContext;
31
import org.openmrs.spring.NoContextPasswordEncoderFactory;
32
import org.slf4j.Logger;
33
import org.slf4j.LoggerFactory;
34
import org.springframework.security.crypto.password.PasswordEncoder;
35
import org.springframework.util.StringUtils;
36

37
/**
38
 * OpenMRS's security class deals with the hashing of passwords.
39
 */
40
public class Security {
41

42
        /**
43
         * encryption settings
44
         */
45
        private static final Logger log = LoggerFactory.getLogger(Security.class);
1 ✔
46

47
        private static final Random RANDOM = new SecureRandom();
1 ✔
48

49
        // required so we can hash passwords at startup when no Spring context is available, for
50
        // example while the database upgrade wizard authenticates a superuser. Which encoders that
51
        // supports is NoContextPasswordEncoderFactory's business, not this class's.
52
        private static final PasswordEncoder FALLBACK_ENCODER = NoContextPasswordEncoderFactory.create();
1 ✔
53
        
54
        private Security() {
55
        }
56
        
57
        static PasswordEncoder getPasswordEncoder() {
58
                if (!ServiceContext.isInstantiated()
1 ✔
59
                                || ServiceContext.getInstance().getApplicationContext() == null) {
1 ✔
60
                        return FALLBACK_ENCODER;
×
61
                }
62
                return Context.getRegisteredComponent("openmrsPasswordEncoder", PasswordEncoder.class);
1 ✔
63
        }
64

65
        /**
66
         * Encodes a password using the configured {@code openmrsPasswordEncoder} and returns the
67
         * full encoded value to persist.
68
         *
69
         * @param strToEncode {@code password + salt} to encode
70
         * @return the encoded value to store
71
         * @since 2.8.10
72
         */
73
        public static String encodePassword(String strToEncode) {
74
                return getPasswordEncoder().encode(strToEncode);
1 ✔
75
        }
76

77
        /**
78
         * Checks a raw password against a stored encoded password using the configured
79
         * {@code PasswordEncoder}.
80
         *
81
         * @param storedEncodedPassword the stored encoded password
82
         * @param rawPassword the raw password, with the salt already concatenated
83
         * @return true if the password matches
84
         * @since 2.8.10
85
         */
86
        public static boolean checkPassword(String storedEncodedPassword, String rawPassword) {
87
                if (rawPassword == null || storedEncodedPassword == null) {
1 ✔
88
                        return false;
1 ✔
89
                }
90
                return getPasswordEncoder().matches(rawPassword, storedEncodedPassword);
1 ✔
91
        }
92

93
        /**
94
         * Compare the given hash and the given string-to-hash to see if they are equal.
95
         *
96
         * @param hashedPassword a stored password that has been hashed previously
97
         * @param passwordToHash a string to encode/hash and compare to hashedPassword
98
         * @return true/false whether the two are equal
99
         * @since 1.5
100
         * <strong>Should</strong> match strings hashed with incorrect sha1 algorithm
101
         * <strong>Should</strong> match strings hashed with sha1 algorithm
102
         * <strong>Should</strong> match strings hashed with sha512 algorithm and 128 characters salt
103
         */
104
        public static boolean hashMatches(String hashedPassword, String passwordToHash) {
105
                if (hashedPassword == null || passwordToHash == null) {
1 ✔
106
                        throw new APIException("password.cannot.be.null", (Object[]) null);
×
107
                }
108
                
109
                return hashedPassword.equals(encodeString(passwordToHash))
1 ✔
110
                        || hashedPassword.equals(encodeStringSHA1(passwordToHash))
1 ✔
111
                        || hashedPassword.equals(incorrectlyEncodeString(passwordToHash));
1 ✔
112
        }
113

114
        /**
115
         * This method will hash <code>strToEncode</code> using the preferred algorithm. Currently,
116
         * OpenMRS's preferred algorithm is hard-coded to be SHA-512.
117
         *
118
         * @param strToEncode string to encode
119
         * @return the SHA-512 encryption of a given string
120
         * <strong>Should</strong> encode strings to 128 characters
121
         */
122
        public static String encodeString(String strToEncode) throws APIException {
123
                return encodeString(strToEncode, "SHA-512");
1 ✔
124
        }
125

126
        /**
127
         * This method will hash <code>strToEncode</code> using the old SHA-1 algorithm.
128
         *
129
         * @param strToEncode string to encode
130
         * @return the SHA-1 encryption of a given string
131
         */
132
        private static String encodeStringSHA1(String strToEncode) throws APIException {
133
                return encodeString(strToEncode, "SHA-1");
1 ✔
134
        }
135

136
        private static String encodeString(String strToEncode, String algorithm) {
137
                return hexString(digest(strToEncode.getBytes(StandardCharsets.UTF_8), algorithm));
1 ✔
138
        }
139

140
        private static byte[] digest(byte[] input, String algorithm) {
141
                MessageDigest md;
142
                try {
143
                        md = MessageDigest.getInstance(algorithm);
1 ✔
144
                }
145
                catch (NoSuchAlgorithmException e) {
×
146
                        // Yikes! Can't encode password...what to do?
147
                        log.error("Can't encode password because the given algorithm: " + algorithm + " was not found! (fail)", e);
×
148
                        throw new APIException("system.cannot.find.encryption.algorithm", null, e);
×
149
                }
1 ✔
150

151
                return md.digest(input);
1 ✔
152
        }
153

154
        /**
155
         * Convenience method to convert a byte array to a string
156
         *
157
         * @param block Byte array to convert to HexString
158
         * @return Hexadecimal string encoding the byte array
159
         */
160
        private static String hexString(byte[] block) {
161
                StringBuilder buf = new StringBuilder();
1 ✔
162
                char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1 ✔
163
                int high;
164
                int low;
165
                for (byte aBlock : block) {
1 ✔
166
                        high = ((aBlock & 0xf0) >> 4);
1 ✔
167
                        low = (aBlock & 0x0f);
1 ✔
168
                        buf.append(hexChars[high]);
1 ✔
169
                        buf.append(hexChars[low]);
1 ✔
170
                }
171

172
                return buf.toString();
1 ✔
173
        }
174

175
        /**
176
         * This method will hash <code>strToEncode</code> using SHA-1 and the incorrect hashing method
177
         * that sometimes dropped out leading zeros.
178
         *
179
         * @param strToEncode string to encode
180
         * @return the SHA-1 encryption of a given string
181
         */
182
        private static String incorrectlyEncodeString(String strToEncode) throws APIException {
183
                return incorrectHexString(digest(strToEncode.getBytes(StandardCharsets.UTF_8), "SHA-1"));
1 ✔
184
        }
185

186
        /**
187
         * This method used to be the simple hexString method, however, as pointed out in ticket
188
         * http://dev.openmrs.org/ticket/1178, it was not working correctly. Authenticated still needs
189
         * to occur against both this method and the correct hex string, so this wrong implementation
190
         * will remain until we either force users to change their passwords, or we just decide to
191
         * invalidate them.
192
         *
193
         * @param b the byte array to encode
194
         * @return the old possibly less than 40 characters hashed string
195
         */
196
        private static String incorrectHexString(byte[] b) {
197
                if (b == null || b.length < 1) {
1 ✔
198
                        return "";
×
199
                }
200
                StringBuilder s = new StringBuilder();
1 ✔
201
                for (byte aB : b) {
1 ✔
202
                        s.append(Integer.toHexString(aB & 0xFF));
1 ✔
203
                }
204
                return new String(s);
1 ✔
205
        }
206

207
        /**
208
         * This method will generate a random string
209
         *
210
         * @return a secure random token.
211
         */
212
        public static String getRandomToken() throws APIException {
213
                byte[] token = new byte[64];
1 ✔
214
                RANDOM.nextBytes(token);
1 ✔
215
                return hexString(digest(token, "SHA-512"));
1 ✔
216
        }
217

218
        /**
219
         * encrypt text to a string with specific initVector and secretKey; rarely used except in
220
         * testing and where specifically necessary
221
         *
222
         * @see #encrypt(String)
223
         *
224
         * @param text string to be encrypted
225
         * @param initVector custom init vector byte array
226
         * @param secretKey custom secret key byte array
227
         * @return encrypted text
228
         * @since 1.9
229
         */
230
        public static String encrypt(String text, byte[] initVector, byte[] secretKey) {
231
                IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
1 ✔
232
                SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
1 ✔
233
                byte[] encrypted;
234
                String result;
235

236
                try {
237
                        Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
1 ✔
238
                        cipher.init(Cipher.ENCRYPT_MODE, secret, initVectorSpec);
1 ✔
239
                        encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
1 ✔
240
                        result = new String(Base64.getEncoder().encode(encrypted), StandardCharsets.UTF_8);
1 ✔
241
                }
242
                catch (GeneralSecurityException e) {
×
243
                        throw new APIException("could.not.encrypt.text", null, e);
×
244
                }
1 ✔
245

246
                return result;
1 ✔
247
        }
248

249
        /**
250
         * encrypt text using stored initVector and securityKey
251
         *
252
         * @param text the text to encrypt
253
         * @return encrypted text
254
         * @since 1.9
255
         * <strong>Should</strong> encrypt short and long text
256
         *
257
         * @deprecated As of version 2.4.0, this method is not referenced in openmrs-core or any other projects under the
258
         * GitHub OpenMRS organisation.
259
         */
260
        @Deprecated
261
        public static String encrypt(String text) {
262
                return Security.encrypt(text, Security.getSavedInitVector(), Security.getSavedSecretKey());
1 ✔
263
        }
264

265
        /**
266
         * decrypt text to a string with specific initVector and secretKey; rarely used except in
267
         * testing and where specifically necessary
268
         *
269
         * @see #decrypt(String)
270
         *
271
         * @param text text to be decrypted
272
         * @param initVector custom init vector byte array
273
         * @param secretKey custom secret key byte array
274
         * @return decrypted text
275
         * @since 1.9
276
         */
277
        public static String decrypt(String text, byte[] initVector, byte[] secretKey) {
278
                IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
1 ✔
279
                SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
1 ✔
280
                String decrypted;
281

282
                try {
283
                        Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
1 ✔
284
                        cipher.init(Cipher.DECRYPT_MODE, secret, initVectorSpec);
1 ✔
285
                        byte[] original = cipher.doFinal(Base64.getDecoder().decode(text));
1 ✔
286
                        decrypted = new String(original, StandardCharsets.UTF_8);
1 ✔
287
                }
288
                catch (GeneralSecurityException e) {
×
289
                        throw new APIException("could.not.decrypt.text", null, e);
×
290
                }
1 ✔
291

292
                return decrypted;
1 ✔
293
        }
294

295
        /**
296
         * decrypt text using stored initVector and securityKey
297
         *
298
         * @param text text to be decrypted
299
         * @return decrypted text
300
         * @since 1.9
301
         * <strong>Should</strong> decrypt short and long text
302
         *
303
         * @deprecated As of version 2.4.0, this method is not referenced in openmrs-core or any other projects under the
304
         * GitHub OpenMRS organisation.
305
         */
306
        @Deprecated
307
        public static String decrypt(String text) {
308
                return Security.decrypt(text, Security.getSavedInitVector(), Security.getSavedSecretKey());
1 ✔
309
        }
310

311
        /**
312
         * retrieve the stored init vector from runtime properties
313
         *
314
         * @return stored init vector byte array
315
         * @since 1.9
316
         */
317
        public static byte[] getSavedInitVector() {
318
                String initVectorText = Context.getRuntimeProperties().getProperty(
1 ✔
319
                        OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY, OpenmrsConstants.ENCRYPTION_VECTOR_DEFAULT);
320

321
                if (StringUtils.hasText(initVectorText)) {
1 ✔
322
                        return Base64.getDecoder().decode(initVectorText);
1 ✔
323
                }
324

325
                throw new APIException("no.encryption.initialization.vector.found", (Object[]) null);
×
326
        }
327

328
        /**
329
         * generate a new cipher initialization vector; should only be called once in order to not
330
         * invalidate all encrypted data
331
         *
332
         * @return a random array of 16 bytes
333
         * @since 1.9
334
         */
335
        public static byte[] generateNewInitVector() {
336
                // initialize the init vector with 16 random bytes
337
                byte[] initVector = new byte[16];
×
338
                RANDOM.nextBytes(initVector);
×
339

340
                return initVector;
×
341
        }
342

343
        /**
344
         * retrieve the secret key from runtime properties
345
         *
346
         * @return stored secret key byte array
347
         * @since 1.9
348
         */
349
        public static byte[] getSavedSecretKey() {
350
                String keyText = Context.getRuntimeProperties().getProperty(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
1 ✔
351
                        OpenmrsConstants.ENCRYPTION_KEY_DEFAULT);
352

353
                if (StringUtils.hasText(keyText)) {
1 ✔
354
                        return Base64.getDecoder().decode(keyText);
1 ✔
355
                }
356

357
                throw new APIException("no.encryption.secret.key.found", (Object[]) null);
×
358
        }
359

360
        /**
361
         * generate a new secret key; should only be called once in order to not invalidate all
362
         * encrypted data
363
         *
364
         * @return generated secret key byte array
365
         * @since 1.9
366
         */
367
        public static byte[] generateNewSecretKey() {
368
                // Get the KeyGenerator
369
                KeyGenerator kgen;
370
                try {
371
                        kgen = KeyGenerator.getInstance(OpenmrsConstants.ENCRYPTION_KEY_SPEC);
×
372
                }
373
                catch (NoSuchAlgorithmException e) {
×
374
                        throw new APIException("could.not.generate.cipher.key", null, e);
×
375
                }
×
376
                kgen.init(128); // 192 and 256 bits may not be available
×
377

378
                // Generate the secret key specs.
379
                SecretKey skey = kgen.generateKey();
×
380

381
                return skey.getEncoded();
×
382
        }
383

384
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc