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

1 package jenkins.security;
2
3 import hudson.util.Secret;
4
5 import javax.crypto.Cipher;
6 import javax.crypto.SecretKey;
7 import javax.crypto.spec.SecretKeySpec;
8 import java.io.IOException;
9 import java.security.GeneralSecurityException;
10
11 /**
12 * {@link ConfidentialKey} that stores a {@link SecretKey} for shared-secret cryptography (AES).
13 *
14 * @author Kohsuke Kawaguchi
15 * @since 1.498
16 */
17 public class CryptoConfidentialKey extends ConfidentialKey {
18 private volatile SecretKey secret;
19 public CryptoConfidentialKey(String id) {
20 super(id);
21 }
22
23 public CryptoConfidentialKey(Class owner, String shortName) {
24 this(owner.getName()+'.'+shortName);
25 }
26
27 private SecretKey getKey() {
28 try {
29 if (secret==null) {
30 synchronized (this) {
31 if (secret==null) {
32 byte[] payload = load();
33 if (payload==null) {
34 payload = ConfidentialStore.get().randomBytes(256);
35 store(payload);
36 }
37 // Due to the stupid US export restriction JDK only ships 128bit version.
38 secret = new SecretKeySpec(payload,0,128/8, ALGORITHM);
39 }
40 }
41 }
42 return secret;
43 } catch (IOException e) {
44 throw new Error("Failed to load the key: "+getId(),e);
45 }
46 }
47
48 /**
49 * Returns a {@link Cipher} object for encrypting with this key.
50 */
51 public Cipher encrypt() {
52 try {
53 Cipher cipher = Secret.getCipher(ALGORITHM);
54 cipher.init(Cipher.ENCRYPT_MODE, getKey());
55 return cipher;
56 } catch (GeneralSecurityException e) {
57 throw new AssertionError(e);
58 }
59 }
60
61 /**
62 * Returns a {@link Cipher} object for decrypting with this key.
63 */
64 public Cipher decrypt() {
65 try {
66 Cipher cipher = Secret.getCipher(ALGORITHM);
67 cipher.init(Cipher.DECRYPT_MODE, getKey());
68 return cipher;
69 } catch (GeneralSecurityException e) {
70 throw new AssertionError(e);
71 }
72 }
73
74
75 private static final String ALGORITHM = "AES";
76 }
77