|
| 1 | +/* |
| 2 | + * Copyright [2007-2025] [wisemapping] |
| 3 | + * |
| 4 | + * Licensed under WiseMapping Public License, Version 1.0 (the "License"). |
| 5 | + * It is basically the Apache License, Version 2.0 (the "License") plus the |
| 6 | + * "powered by wisemapping" text requirement on every single page; |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the license at |
| 9 | + * |
| 10 | + * https://github.com/wisemapping/wisemapping-open-source/blob/main/LICENSE.md |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package com.wisemapping.security; |
| 19 | + |
| 20 | +import org.jetbrains.annotations.NotNull; |
| 21 | +import org.jetbrains.annotations.Nullable; |
| 22 | +import org.slf4j.Logger; |
| 23 | +import org.slf4j.LoggerFactory; |
| 24 | +import org.springframework.beans.factory.annotation.Value; |
| 25 | +import org.springframework.stereotype.Service; |
| 26 | + |
| 27 | +import javax.crypto.Cipher; |
| 28 | +import javax.crypto.SecretKey; |
| 29 | +import javax.crypto.spec.IvParameterSpec; |
| 30 | +import javax.crypto.spec.SecretKeySpec; |
| 31 | +import java.nio.charset.StandardCharsets; |
| 32 | +import java.security.MessageDigest; |
| 33 | +import java.util.Base64; |
| 34 | + |
| 35 | +/** |
| 36 | + * Service for encrypting and decrypting OAuth provider user IDs (stored in the |
| 37 | + * {@code oauth_token} database column). |
| 38 | + * |
| 39 | + * <h3>Backward-compatibility</h3> |
| 40 | + * <p>Encrypted values carry an <b>{@value #ENC_PREFIX}</b> prefix. Any value that |
| 41 | + * lacks this prefix is treated as legacy plaintext and returned unchanged by |
| 42 | + * {@link #decrypt}. This allows old rows and new rows to coexist in the same table |
| 43 | + * without a schema migration. |
| 44 | + * |
| 45 | + * <h3>Deterministic encryption</h3> |
| 46 | + * <p>AES-256-CBC is used with a <em>fixed</em> IV derived from the secret key. |
| 47 | + * The same plaintext therefore always produces the same ciphertext for a given key. |
| 48 | + * This is intentional: it lets JPQL {@code IN} queries match both the plaintext and |
| 49 | + * encrypted forms of a provider ID without requiring an extra hash column. |
| 50 | + * |
| 51 | + * <h3>Disabled mode</h3> |
| 52 | + * <p>When {@code app.oauth.token.secret} is empty (the default) the service acts as |
| 53 | + * a no-op: {@link #encrypt} returns the original value and {@link #decrypt} returns |
| 54 | + * the stored value unchanged. This preserves existing behaviour for deployments that |
| 55 | + * have not yet opted in to encryption. |
| 56 | + */ |
| 57 | +@Service |
| 58 | +public class OAuthTokenEncryptionService { |
| 59 | + |
| 60 | + /** Prefix prepended to every encrypted value to distinguish it from plaintext. */ |
| 61 | + public static final String ENC_PREFIX = "{enc}"; |
| 62 | + |
| 63 | + private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; |
| 64 | + private static final Logger logger = LoggerFactory.getLogger(OAuthTokenEncryptionService.class); |
| 65 | + |
| 66 | + @Value("${app.oauth.token.secret:}") |
| 67 | + private String secretKey; |
| 68 | + |
| 69 | + // Derived lazily and cached after first use (guarded by synchronized helpers). |
| 70 | + private volatile SecretKey aesKey; |
| 71 | + private volatile IvParameterSpec iv; |
| 72 | + |
| 73 | + // ------------------------------------------------------------------------- |
| 74 | + // Public API |
| 75 | + // ------------------------------------------------------------------------- |
| 76 | + |
| 77 | + /** |
| 78 | + * Encrypt a plaintext OAuth provider user ID. |
| 79 | + * |
| 80 | + * @param plaintext the raw provider ID (e.g. a Google subject or Facebook user ID) |
| 81 | + * @return {@code {enc}<base64-ciphertext>} when encryption is enabled, |
| 82 | + * or {@code plaintext} unchanged when no secret key is configured |
| 83 | + */ |
| 84 | + @Nullable |
| 85 | + public String encrypt(@Nullable String plaintext) { |
| 86 | + if (plaintext == null) return null; |
| 87 | + if (!isEnabled()) return plaintext; |
| 88 | + try { |
| 89 | + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); |
| 90 | + cipher.init(Cipher.ENCRYPT_MODE, resolveKey(), resolveIv()); |
| 91 | + byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); |
| 92 | + return ENC_PREFIX + Base64.getEncoder().encodeToString(encrypted); |
| 93 | + } catch (Exception e) { |
| 94 | + logger.error("Failed to encrypt OAuth token", e); |
| 95 | + throw new IllegalStateException("OAuth token encryption failed", e); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Decrypt a value previously produced by {@link #encrypt}. |
| 101 | + * |
| 102 | + * <p>If the value does not start with the {@value #ENC_PREFIX} prefix it is |
| 103 | + * returned as-is (legacy plaintext / already-decrypted value). |
| 104 | + * |
| 105 | + * @param value the stored column value |
| 106 | + * @return the original provider ID, or {@code value} unchanged for plaintext rows |
| 107 | + */ |
| 108 | + @Nullable |
| 109 | + public String decrypt(@Nullable String value) { |
| 110 | + if (value == null || !value.startsWith(ENC_PREFIX)) return value; |
| 111 | + if (!isEnabled()) { |
| 112 | + logger.warn("Encountered an encrypted OAuth token but no secret key is configured — returning raw value"); |
| 113 | + return value; |
| 114 | + } |
| 115 | + try { |
| 116 | + byte[] cipherBytes = Base64.getDecoder().decode(value.substring(ENC_PREFIX.length())); |
| 117 | + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); |
| 118 | + cipher.init(Cipher.DECRYPT_MODE, resolveKey(), resolveIv()); |
| 119 | + return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8); |
| 120 | + } catch (Exception e) { |
| 121 | + logger.error("Failed to decrypt OAuth token", e); |
| 122 | + throw new IllegalStateException("OAuth token decryption failed", e); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Returns {@code true} when the value carries the encrypted prefix. |
| 128 | + */ |
| 129 | + public boolean isEncrypted(@Nullable String value) { |
| 130 | + return value != null && value.startsWith(ENC_PREFIX); |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Returns {@code true} when a non-empty secret key has been configured. |
| 135 | + */ |
| 136 | + public boolean isEnabled() { |
| 137 | + return secretKey != null && !secretKey.isBlank(); |
| 138 | + } |
| 139 | + |
| 140 | + // ------------------------------------------------------------------------- |
| 141 | + // Key / IV derivation |
| 142 | + // ------------------------------------------------------------------------- |
| 143 | + |
| 144 | + private SecretKey resolveKey() throws Exception { |
| 145 | + if (aesKey == null) { |
| 146 | + synchronized (this) { |
| 147 | + if (aesKey == null) { |
| 148 | + aesKey = deriveKey(secretKey); |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + return aesKey; |
| 153 | + } |
| 154 | + |
| 155 | + private IvParameterSpec resolveIv() throws Exception { |
| 156 | + if (iv == null) { |
| 157 | + synchronized (this) { |
| 158 | + if (iv == null) { |
| 159 | + iv = deriveIv(secretKey); |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + return iv; |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Derive a 256-bit AES key from the secret string via SHA-256. |
| 168 | + */ |
| 169 | + private static SecretKey deriveKey(@NotNull String secret) throws Exception { |
| 170 | + MessageDigest sha = MessageDigest.getInstance("SHA-256"); |
| 171 | + byte[] keyBytes = sha.digest(secret.getBytes(StandardCharsets.UTF_8)); |
| 172 | + return new SecretKeySpec(keyBytes, "AES"); |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * Derive a deterministic 128-bit IV from the secret via MD5. |
| 177 | + * |
| 178 | + * <p>The IV is intentionally fixed for a given key so that encryption is |
| 179 | + * deterministic (same plaintext → same ciphertext). This is a deliberate |
| 180 | + * trade-off that makes JPQL equality and IN-list lookups possible without |
| 181 | + * storing a separate hash column. |
| 182 | + */ |
| 183 | + private static IvParameterSpec deriveIv(@NotNull String secret) throws Exception { |
| 184 | + MessageDigest md5 = MessageDigest.getInstance("MD5"); |
| 185 | + byte[] ivBytes = md5.digest(secret.getBytes(StandardCharsets.UTF_8)); |
| 186 | + return new IvParameterSpec(ivBytes); |
| 187 | + } |
| 188 | +} |
0 commit comments