File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\util\Secret.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.util;
25
26 import com.thoughtworks.xstream.converters.Converter;
27 import com.thoughtworks.xstream.converters.MarshallingContext;
28 import com.thoughtworks.xstream.converters.UnmarshallingContext;
29 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
30 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
31 import com.trilead.ssh2.crypto.Base64;
32 import jenkins.model.Jenkins;
33 import hudson.Util;
34 import jenkins.security.CryptoConfidentialKey;
35 import org.kohsuke.stapler.Stapler;
36
37 import javax.crypto.SecretKey;
38 import javax.crypto.Cipher;
39 import java.io.Serializable;
40 import java.io.UnsupportedEncodingException;
41 import java.io.IOException;
42 import java.security.GeneralSecurityException;
43
44 /**
45 * Glorified {@link String} that uses encryption in the persisted form, to avoid accidental exposure of a secret.
46 *
47 * <p>
48 * This is not meant as a protection against code running in the same VM, nor against an attacker
49 * who has local file system access on Jenkins master.
50 *
51 * <p>
52 * {@link Secret}s can correctly read-in plain text password, so this allows the existing
53 * String field to be updated to {@link Secret}.
54 *
55 * @author Kohsuke Kawaguchi
56 */
57 public final class Secret implements Serializable {
58 /**
59 * Unencrypted secret text.
60 */
61 private final String value;
62
63 private Secret(String value) {
64 this.value = value;
65 }
66
67 /**
68 * Obtains the secret in a plain text.
69 *
70 * @see #getEncryptedValue()
71 * @deprecated as of 1.356
72 * Use {@link #toString(Secret)} to avoid NPE in case Secret is null.
73 * Or if you really know what you are doing, use the {@link #getPlainText()} method.
74 */
75 @Override
76 public String toString() {
77 return value;
78 }
79
80 /**
81 * Obtains the plain text password.
82 * Before using this method, ask yourself if you'd be better off using {@link Secret#toString(Secret)}
83 * to avoid NPE.
84 */
85 public String getPlainText() {
86 return value;
87 }
88
89 @Override
90 public boolean equals(Object that) {
91 return that instanceof Secret && value.equals(((Secret)that).value);
92 }
93
94 @Override
95 public int hashCode() {
96 return value.hashCode();
97 }
98
99 /**
100 * Turns {@link Jenkins#getSecretKey()} into an AES key.
101 *
102 * @deprecated
103 * This is no longer the key we use to encrypt new information, but we still need this
104 * to be able to decrypt what's already persisted.
105 */
106 /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException {
107 String secret = SECRET;
108 if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128();
109 return Util.toAes128Key(secret);
110 }
111
112 /**
113 * Encrypts {@link #value} and returns it in an encoded printable form.
114 *
115 * @see #toString()
116 */
117 public String getEncryptedValue() {
118 try {
119 Cipher cipher = KEY.encrypt();
120 // add the magic suffix which works like a check sum.
121 return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8"))));
122 } catch (GeneralSecurityException e) {
123 throw new Error(e); // impossible
124 } catch (UnsupportedEncodingException e) {
125 throw new Error(e); // impossible
126 }
127 }
128
129 /**
130 * Reverse operation of {@link #getEncryptedValue()}. Returns null
131 * if the given cipher text was invalid.
132 */
133 public static Secret decrypt(String data) {
134 if(data==null) return null;
135 try {
136 byte[] in = Base64.decode(data.toCharArray());
137 Secret s = tryDecrypt(KEY.decrypt(), in);
138 if (s!=null) return s;
139
140 // try our historical key for backward compatibility
141 Cipher cipher = getCipher("AES");
142 cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());
143 return tryDecrypt(cipher, in);
144 } catch (GeneralSecurityException e) {
145 return null;
146 } catch (UnsupportedEncodingException e) {
147 throw new Error(e); // impossible
148 } catch (IOException e) {
149 return null;
150 }
151 }
152
153 /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {
154 try {
155 String plainText = new String(cipher.doFinal(in), "UTF-8");
156 if(plainText.endsWith(MAGIC))
157 return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));
158 return null;
159 } catch (GeneralSecurityException e) {
160 return null; // if the key doesn't match with the bytes, it can result in BadPaddingException
161 }
162 }
163
164 /**
165 * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862
166 * This method uses specific provider selected via hudson.util.Secret.provider system property
167 * to provide a workaround for the above bug where default provide gives an unusable instance.
168 * (Glassfish Enterprise users should set value of this property to "SunJCE")
169 */
170 public static Cipher getCipher(String algorithm) throws GeneralSecurityException {
171 return PROVIDER != null ? Cipher.getInstance(algorithm, PROVIDER)
172 : Cipher.getInstance(algorithm);
173 }
174
175 /**
176 * Attempts to treat the given string first as a cipher text, and if it doesn't work,
177 * treat the given string as the unencrypted secret value.
178 *
179 * <p>
180 * Useful for recovering a value from a form field.
181 *
182 * @return never null
183 */
184 public static Secret fromString(String data) {
185 data = Util.fixNull(data);
186 Secret s = decrypt(data);
187 if(s==null) s=new Secret(data);
188 return s;
189 }
190
191 /**
192 * Works just like {@link Secret#toString()} but avoids NPE when the secret is null.
193 * To be consistent with {@link #fromString(String)}, this method doesn't distinguish
194 * empty password and null password.
195 */
196 public static String toString(Secret s) {
197 return s==null ? "" : s.value;
198 }
199
200 public static final class ConverterImpl implements Converter {
201 public ConverterImpl() {
202 }
203
204 public boolean canConvert(Class type) {
205 return type==Secret.class;
206 }
207
208 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
209 Secret src = (Secret) source;
210 writer.setValue(src.getEncryptedValue());
211 }
212
213 public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
214 return fromString(reader.getValue());
215 }
216 }
217
218 private static final String MAGIC = "::::MAGIC::::";
219
220 /**
221 * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862
222 * @see #getCipher(String)
223 */
224 private static final String PROVIDER = System.getProperty(Secret.class.getName()+".provider");
225
226 /**
227 * For testing only. Override the secret key so that we can test this class without {@link Jenkins}.
228 */
229 /*package*/ static String SECRET = null;
230
231 /**
232 * The key that encrypts the data on disk.
233 */
234 private static final CryptoConfidentialKey KEY = new CryptoConfidentialKey(Secret.class.getName());
235
236 private static final long serialVersionUID = 1L;
237
238 static {
239 Stapler.CONVERT_UTILS.register(new org.apache.commons.beanutils.Converter() {
240 public Secret convert(Class type, Object value) {
241 return Secret.fromString(value.toString());
242 }
243 }, Secret.class);
244 }
245 }
246