提交 d9aa1283 编写于 作者: I Ivan Fernandez Calvo 提交者: Wadeck Follonier

[JENKINS-43780] Remove references to Trilead classes (#3876)

* [JENKINS-43780] Remove references to Trilead classes

* Update JSONSignatureValidator.java, Scrambler.java, ConsistentHash.java
上级 cc964ef6
......@@ -25,7 +25,6 @@
*/
package hudson.console;
import com.trilead.ssh2.crypto.Base64;
import jenkins.model.Jenkins;
import hudson.remoting.ObjectInputStreamEx;
import java.util.concurrent.TimeUnit;
......@@ -48,6 +47,9 @@ import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
......@@ -119,16 +121,15 @@ public class AnnotatedLargeText<T> extends LargeText {
if (base64!=null) {
Cipher sym = PASSING_ANNOTATOR.decrypt();
ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(
new CipherInputStream(new ByteArrayInputStream(Base64.decode(base64.toCharArray())),sym)),
Jenkins.getInstance().pluginManager.uberClassLoader);
try {
try (ObjectInputStream ois = new ObjectInputStreamEx(new GZIPInputStream(
new CipherInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8))), sym)),
Jenkins.getInstance().pluginManager.uberClassLoader)) {
long timestamp = ois.readLong();
if (TimeUnit.HOURS.toMillis(1) > abs(System.currentTimeMillis()-timestamp))
// don't deserialize something too old to prevent a replay attack
return (ConsoleAnnotator)ois.readObject();
} finally {
ois.close();
return (ConsoleAnnotator) ois.readObject();
} catch (RuntimeException ex) {
throw new IOException("Could not decode input", ex);
}
}
} catch (ClassNotFoundException e) {
......@@ -176,7 +177,7 @@ public class AnnotatedLargeText<T> extends LargeText {
oos.close();
StaplerResponse rsp = Stapler.getCurrentResponse();
if (rsp!=null)
rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
rsp.setHeader("X-ConsoleAnnotator", new String(Base64.getEncoder().encode(baos.toByteArray())));
return r;
}
......
......@@ -23,7 +23,6 @@
*/
package hudson.model;
import com.trilead.ssh2.crypto.Base64;
import hudson.PluginWrapper;
import hudson.Util;
import hudson.Extension;
......@@ -58,6 +57,7 @@ import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import com.jcraft.jzlib.GZIPOutputStream;
import jenkins.util.SystemProperties;
......@@ -185,7 +185,7 @@ public class UsageStatistics extends PageDecorator implements PersistentDescript
o.write(w);
}
return new String(Base64.encode(baos.toByteArray()));
return new String(Base64.getEncoder().encode(baos.toByteArray()));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
}
......
......@@ -23,8 +23,9 @@
*/
package hudson.util;
import com.trilead.ssh2.crypto.digest.MD5;
import java.lang.RuntimeException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
......@@ -289,15 +290,18 @@ public class ConsistentHash<T> {
* Compresses a string into an integer with MD5.
*/
private int md5(String s) {
MD5 md5 = new MD5();
md5.update(s.getBytes());
byte[] digest = new byte[16];
md5.digest(digest);
// 16 bytes -> 4 bytes
for (int i=0; i<4; i++)
digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12];
return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]);
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes());
byte[] digest = md5.digest();
// 16 bytes -> 4 bytes
for (int i=0; i<4; i++)
digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12];
return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]);
} catch (GeneralSecurityException e) {
throw new RuntimeException("Could not generate MD5 hash", e);
}
}
/**
......
......@@ -622,9 +622,9 @@ public abstract class FormFieldValidator {
return;
}
com.trilead.ssh2.crypto.Base64.decode(v.toCharArray());
java.util.Base64.getDecoder().decode(v);
ok();
} catch (IOException e) {
} catch (IOException | IllegalArgumentException e) {
fail();
}
}
......
......@@ -54,7 +54,9 @@ import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
......@@ -461,9 +463,9 @@ public abstract class FormValidation extends IOException implements HttpResponse
if(!allowEmpty && v.length()==0)
return error(errorMessage);
com.trilead.ssh2.crypto.Base64.decode(v.toCharArray());
Base64.getDecoder().decode(v.getBytes(StandardCharsets.UTF_8));
return ok();
} catch (IOException e) {
} catch (IllegalArgumentException e) {
return error(errorMessage);
}
}
......
......@@ -24,7 +24,6 @@
*/
package hudson.util;
import com.trilead.ssh2.crypto.Base64;
import hudson.Util;
import jenkins.model.Jenkins;
import jenkins.security.CryptoConfidentialKey;
......@@ -34,7 +33,9 @@ import org.kohsuke.accmod.restrictions.NoExternalUse;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.UTF_8;
......@@ -45,7 +46,12 @@ import static java.nio.charset.StandardCharsets.UTF_8;
public class HistoricalSecrets {
/*package*/ static Secret decrypt(String data, CryptoConfidentialKey key) throws IOException, GeneralSecurityException {
byte[] in = Base64.decode(data.toCharArray());
byte[] in;
try {
in = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
} catch (IllegalArgumentException ex) {
throw new IOException("Could not decode secret", ex);
}
Secret s = tryDecrypt(key.decrypt(), in);
if (s!=null) return s;
......
......@@ -26,12 +26,11 @@ package hudson.util;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import com.trilead.ssh2.crypto.Base64;
/**
* Encrypt/decrypt data by using a "session" key that only lasts for
......@@ -49,11 +48,9 @@ public class Protector {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, DES_KEY);
return new String(Base64.encode(cipher.doFinal((secret+ MAGIC).getBytes("UTF-8"))));
return new String(Base64.getEncoder().encode(cipher.doFinal((secret+ MAGIC).getBytes(StandardCharsets.UTF_8))));
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
}
......@@ -65,15 +62,11 @@ public class Protector {
try {
Cipher cipher = Secret.getCipher(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, DES_KEY);
String plainText = new String(cipher.doFinal(Base64.decode(data.toCharArray())), "UTF-8");
String plainText = new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8))), StandardCharsets.UTF_8);
if(plainText.endsWith(MAGIC))
return plainText.substring(0,plainText.length()-3);
return null;
} catch (GeneralSecurityException e) {
return null;
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
} catch (IOException e) {
} catch (GeneralSecurityException | IllegalArgumentException e) {
return null;
}
}
......
......@@ -23,10 +23,10 @@
*/
package hudson.util;
import com.trilead.ssh2.crypto.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Scrambles, but does not encrypt, text.
......@@ -37,20 +37,19 @@ import java.io.UnsupportedEncodingException;
* @see Protector
*/
public class Scrambler {
private static final Logger LOGGER = Logger.getLogger(Scrambler.class.getName());
public static String scramble(String secret) {
if(secret==null) return null;
try {
return new String(Base64.encode(secret.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
return new String(Base64.getEncoder().encode(secret.getBytes(StandardCharsets.UTF_8)));
}
public static String descramble(String scrambled) {
if(scrambled==null) return null;
try {
return new String(Base64.decode(scrambled.toCharArray()),"UTF-8");
} catch (IOException e) {
return new String(Base64.getDecoder().decode(scrambled.getBytes(StandardCharsets.UTF_8)),StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.WARNING,"Corrupted data", e);
return ""; // corrupted data.
}
}
......
......@@ -29,7 +29,6 @@ import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.trilead.ssh2.crypto.Base64;
import jenkins.util.SystemProperties;
import java.util.Arrays;
import jenkins.model.Jenkins;
......@@ -42,6 +41,7 @@ import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Base64;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
......@@ -149,7 +149,7 @@ public final class Secret implements Serializable {
System.arraycopy(iv, 0, payload, pos, iv.length);
pos+=iv.length;
System.arraycopy(encrypted, 0, payload, pos, encrypted.length);
return "{"+new String(Base64.encode(payload))+"}";
return "{"+new String(Base64.getEncoder().encode(payload))+"}";
} catch (GeneralSecurityException e) {
throw new Error(e); // impossible
}
......@@ -175,8 +175,8 @@ public final class Secret implements Serializable {
if (data.startsWith("{") && data.endsWith("}")) { //likely CBC encrypted/containing metadata but could be plain text
byte[] payload;
try {
payload = Base64.decode(data.substring(1, data.length()-1).toCharArray());
} catch (IOException e) {
payload = Base64.getDecoder().decode(data.substring(1, data.length()-1));
} catch (IllegalArgumentException e) {
return null;
}
switch (payload[0]) {
......
package hudson.util;
import com.trilead.ssh2.crypto.Base64;
import hudson.Functions;
import hudson.model.TaskListener;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import javax.crypto.Cipher;
......@@ -12,13 +12,13 @@ import javax.crypto.SecretKey;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.LinkOption;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;
......@@ -62,8 +62,8 @@ public class SecretRewriter {
byte[] in;
try {
in = Base64.decode(s.toCharArray());
} catch (IOException e) {
in = Base64.getDecoder().decode(s.getBytes(StandardCharsets.UTF_8));
} catch (IllegalArgumentException e) {
return s; // not a valid base64
}
cipher.init(Cipher.DECRYPT_MODE, key);
......
package jenkins.util;
import com.trilead.ssh2.crypto.Base64;
import hudson.util.FormValidation;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import jenkins.model.Jenkins;
......@@ -36,6 +35,7 @@ import java.security.cert.CertificateNotYetValidException;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
......@@ -70,16 +70,20 @@ public class JSONSignatureValidator {
{// load and verify certificates
CertificateFactory cf = CertificateFactory.getInstance("X509");
for (Object cert : signature.getJSONArray("certificates")) {
X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
try {
c.checkValidity();
} catch (CertificateExpiredException e) { // even if the certificate isn't valid yet, we'll proceed it anyway
warning = FormValidation.warning(e,String.format("Certificate %s has expired in %s",cert.toString(),name));
} catch (CertificateNotYetValidException e) {
warning = FormValidation.warning(e,String.format("Certificate %s is not yet valid in %s",cert.toString(),name));
X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(cert.toString().getBytes(StandardCharsets.UTF_8))));
try {
c.checkValidity();
} catch (CertificateExpiredException e) { // even if the certificate isn't valid yet, we'll proceed it anyway
warning = FormValidation.warning(e, String.format("Certificate %s has expired in %s", cert.toString(), name));
} catch (CertificateNotYetValidException e) {
warning = FormValidation.warning(e, String.format("Certificate %s is not yet valid in %s", cert.toString(), name));
}
LOGGER.log(Level.FINE, "Add certificate found in json doc: \r\n\tsubjectDN: {0}\r\n\tissuer: {1}", new Object[]{c.getSubjectDN(), c.getIssuerDN()});
certs.add(c);
} catch (IllegalArgumentException ex) {
throw new IOException("Could not decode certificate", ex);
}
LOGGER.log(Level.FINE, "Add certificate found in json doc: \r\n\tsubjectDN: {0}\r\n\tissuer: {1}", new Object[]{c.getSubjectDN(), c.getIssuerDN()});
certs.add(c);
}
CertificateUtil.validatePath(certs, loadTrustAnchors(cf));
......@@ -220,10 +224,10 @@ public class JSONSignatureValidator {
}
try {
if (signature.verify(Base64.decode(providedSignature.toCharArray()))) {
if (signature.verify(Base64.getDecoder().decode(providedSignature))) {
return true;
}
} catch (SignatureException|IOException ignore) {
} catch (SignatureException|IllegalArgumentException ignore) {
// ignore
}
return false;
......@@ -233,7 +237,7 @@ public class JSONSignatureValidator {
* Utility method supporting both possible digest formats: Base64 and Hex
*/
private boolean digestMatches(byte[] digest, String providedDigest) {
return providedDigest.equalsIgnoreCase(Hex.encodeHexString(digest)) || providedDigest.equalsIgnoreCase(new String(Base64.encode(digest)));
return providedDigest.equalsIgnoreCase(Hex.encodeHexString(digest)) || providedDigest.equalsIgnoreCase(new String(Base64.getEncoder().encode(digest)));
}
......
package hudson.util;
import com.trilead.ssh2.crypto.Base64;
import hudson.FilePath;
import hudson.Functions;
import hudson.model.TaskListener;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
......@@ -60,7 +60,7 @@ public class SecretRewriterTest {
private String encryptOld(String str) throws Exception {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, HistoricalSecrets.getLegacyKey());
return new String(Base64.encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes("UTF-8"))));
return new String(Base64.getEncoder().encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes("UTF-8"))));
}
private String encryptNew(String str) {
......
......@@ -24,7 +24,7 @@
package hudson.util;
import com.trilead.ssh2.crypto.Base64;
import java.util.Base64;
import java.util.Random;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
......@@ -124,7 +124,7 @@ public class SecretTest {
for (String str : new String[] {"Hello world", "", "\u0000unprintable"}) {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, legacy);
String old = new String(Base64.encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes("UTF-8"))));
String old = new String(Base64.getEncoder().encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes("UTF-8"))));
Secret s = Secret.fromString(old);
assertEquals("secret by the old key should decrypt", str, s.getPlainText());
assertNotEquals("but when encrypting, ConfidentialKey should be in use", old, s.getEncryptedValue());
......
......@@ -23,14 +23,15 @@
*/
package hudson.model;
import com.trilead.ssh2.crypto.Base64;
import java.util.concurrent.TimeUnit;
import net.sf.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Date;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
......@@ -66,7 +67,7 @@ public class UpdateCenterTest {
CertificateFactory cf = CertificateFactory.getInstance("X509");
JSONObject signature = json.getJSONObject("signature");
for (Object cert : signature.getJSONArray("certificates")) {
X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(cert.toString().getBytes(StandardCharsets.UTF_8))));
c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
}
}
......
......@@ -24,10 +24,13 @@
package hudson.model;
import com.google.common.io.Resources;
import com.trilead.ssh2.crypto.Base64;
import hudson.ClassicPluginStrategy;
import hudson.Util;
import hudson.model.UsageStatistics.CombinedCipherInputStream;
import hudson.node_monitors.ArchitectureMonitor;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Set;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
......@@ -85,7 +88,7 @@ public class UsageStatisticsTest {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey priv = (RSAPrivateKey)keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Util.fromHexString(privateKey)));
byte[] cipherText = Base64.decode(data.toCharArray());
byte[] cipherText = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
InputStreamReader r = new InputStreamReader(new GZIPInputStream(
new CombinedCipherInputStream(new ByteArrayInputStream(cipherText),priv,"AES")), "UTF-8");
JSONObject o = JSONObject.fromObject(IOUtils.toString(r));
......
......@@ -5,7 +5,6 @@ import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.trilead.ssh2.crypto.Base64;
import hudson.FilePath;
import hudson.Util;
import hudson.util.Secret;
......@@ -20,6 +19,7 @@ import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Base64;
import java.util.regex.Pattern;
import java.util.stream.Stream;
......@@ -163,7 +163,7 @@ public class RekeySecretAdminMonitorTest extends HudsonTestCase {
private String encryptOld(String str) throws Exception {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, Util.toAes128Key(TEST_KEY));
return new String(Base64.encode(cipher.doFinal((str + "::::MAGIC::::").getBytes("UTF-8"))));
return new String(Base64.getEncoder().encode(cipher.doFinal((str + "::::MAGIC::::").getBytes("UTF-8"))));
}
private String encryptNew(String str) {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册