Use Java's Base64 instead of elasticsearch's. elastic/elasticsearch#2282

Original commit: elastic/x-pack-elasticsearch@c2e748d732
This commit is contained in:
Adrien Grand 2016-05-18 09:20:25 +02:00
parent a0f826c8ed
commit 6860944f07
17 changed files with 65 additions and 72 deletions

View File

@ -6,8 +6,6 @@
package org.elasticsearch.license.core;
import org.elasticsearch.common.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
@ -27,6 +25,7 @@ import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class CryptUtils {
private static final int minimumPadding = 20;
@ -251,6 +250,6 @@ public class CryptUtils {
private static char[] hashPassPhrase(String passPhrase) throws NoSuchAlgorithmException {
final byte[] passBytes = passPhrase.getBytes(StandardCharsets.UTF_8);
final byte[] digest = MessageDigest.getInstance(passHashAlgorithm).digest(passBytes);
return new String(Base64.encodeBytesToBytes(digest), StandardCharsets.UTF_8).toCharArray();
return Base64.getEncoder().encodeToString(digest).toCharArray();
}
}

View File

@ -8,7 +8,6 @@ package org.elasticsearch.license.core;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
@ -20,6 +19,7 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
@ -388,7 +388,7 @@ public class License implements ToXContent {
}
// not a license spec
if (builder.signature != null) {
byte[] signatureBytes = Base64.decode(builder.signature);
byte[] signatureBytes = Base64.getDecoder().decode(builder.signature);
ByteBuffer byteBuffer = ByteBuffer.wrap(signatureBytes);
int version = byteBuffer.getInt();
// we take the absolute version, because negative versions
@ -415,10 +415,10 @@ public class License implements ToXContent {
*/
public static boolean isAutoGeneratedLicense(String signature) {
try {
byte[] signatureBytes = Base64.decode(signature);
byte[] signatureBytes = Base64.getDecoder().decode(signature);
ByteBuffer byteBuffer = ByteBuffer.wrap(signatureBytes);
return byteBuffer.getInt() < 0;
} catch (IOException e) {
} catch (IllegalArgumentException e) {
throw new IllegalStateException(e);
}
}

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.license.core;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@ -18,6 +17,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
/**
@ -35,7 +35,7 @@ public class LicenseVerifier {
byte[] signedContent = null;
byte[] signatureHash = null;
try {
byte[] signatureBytes = Base64.decode(license.signature());
byte[] signatureBytes = Base64.getDecoder().decode(license.signature());
ByteBuffer byteBuffer = ByteBuffer.wrap(signatureBytes);
int version = byteBuffer.getInt();
int magicLen = byteBuffer.getInt();
@ -53,7 +53,7 @@ public class LicenseVerifier {
rsa.initVerify(CryptUtils.readEncryptedPublicKey(encryptedPublicKeyData));
rsa.update(contentBuilder.bytes().toBytes());
return rsa.verify(signedContent)
&& Arrays.equals(Base64.encodeBytesToBytes(encryptedPublicKeyData), signatureHash);
&& Arrays.equals(Base64.getEncoder().encode(encryptedPublicKeyData), signatureHash);
} catch (IOException | NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
throw new IllegalStateException(e);
} finally {

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.license.licensor;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@ -22,6 +21,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Base64;
import java.util.Collections;
/**
@ -63,7 +63,7 @@ public class LicenseSigner {
final byte[] magic = new byte[MAGIC_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(magic);
final byte[] hash = Base64.encodeBytesToBytes(Files.readAllBytes(publicKeyPath));
final byte[] hash = Base64.getEncoder().encode(Files.readAllBytes(publicKeyPath));
assert hash != null;
byte[] bytes = new byte[4 + 4 + MAGIC_LENGTH + 4 + hash.length + 4 + signedContent.length];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
@ -76,7 +76,7 @@ public class LicenseSigner {
.put(signedContent);
return License.builder()
.fromLicenseSpec(licenseSpec, Base64.encodeBytes(bytes))
.fromLicenseSpec(licenseSpec, Base64.getEncoder().encodeToString(bytes))
.build();
}
}

View File

@ -10,7 +10,6 @@ import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.Streams;
@ -60,6 +59,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@ -214,7 +214,7 @@ public class SearchTransformIT extends ESIntegTestCase {
assertThat(map.get("query"), instanceOf(String.class));
String queryAsBase64 = (String) map.get("query");
String decodedQuery = new String(Base64.decode(queryAsBase64), StandardCharsets.UTF_8);
String decodedQuery = new String(Base64.getDecoder().decode(queryAsBase64), StandardCharsets.UTF_8);
assertThat(decodedQuery, containsString("_unknown_query_"));
}

View File

@ -9,7 +9,6 @@ import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.AbstractDiffable;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContent;
@ -21,6 +20,7 @@ import org.elasticsearch.license.core.License;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
@ -114,7 +114,7 @@ public class LicensesMetaData extends AbstractDiffable<MetaData.Custom> implemen
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
if (parser.currentToken().isValue()) {
// trial license
byte[] data = decrypt(Base64.decode(parser.text()));
byte[] data = decrypt(Base64.getDecoder().decode(parser.text()));
try (XContentParser trialLicenseParser =
XContentFactory.xContent(XContentType.JSON).createParser(data)) {
trialLicenseParser.nextToken();
@ -186,7 +186,7 @@ public class LicensesMetaData extends AbstractDiffable<MetaData.Custom> implemen
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
license.toXContent(contentBuilder,
new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
streamOutput.writeString(Base64.encodeBytes(encrypt(contentBuilder.bytes().toBytes())));
streamOutput.writeString(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes())));
}
} else {
if (license == LICENSE_TOMBSTONE) {
@ -209,7 +209,7 @@ public class LicensesMetaData extends AbstractDiffable<MetaData.Custom> implemen
}
int numTrialLicenses = streamInput.readVInt();
for (int i = 0; i < numTrialLicenses; i++) {
byte[] data = decrypt(Base64.decode(streamInput.readString()));
byte[] data = decrypt(Base64.getDecoder().decode(streamInput.readString()));
try (XContentParser trialLicenseParser = XContentFactory.xContent(XContentType.JSON).createParser(data)) {
trialLicenseParser.nextToken();
License pre20TrialLicense = License.fromXContent(trialLicenseParser);

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.license.plugin.core;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
@ -15,6 +14,7 @@ import org.elasticsearch.license.core.License;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Collections;
import static org.elasticsearch.license.core.CryptUtils.decrypt;
@ -39,7 +39,7 @@ public class TrialLicense {
byteBuffer.putInt(-License.VERSION_CURRENT)
.putInt(encrypt.length)
.put(encrypt);
signature = Base64.encodeBytes(bytes);
signature = Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
throw new IllegalStateException(e);
}
@ -48,7 +48,7 @@ public class TrialLicense {
public static boolean verify(final License license) {
try {
byte[] signatureBytes = Base64.decode(license.signature());
byte[] signatureBytes = Base64.getDecoder().decode(license.signature());
ByteBuffer byteBuffer = ByteBuffer.wrap(signatureBytes);
int version = byteBuffer.getInt();
int contentLen = byteBuffer.getInt();

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.license.plugin;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
@ -17,6 +16,7 @@ import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;
@ -102,7 +102,7 @@ public class TrialLicenseTests extends ESTestCase {
byteBuffer.putInt(-spec.version())
.putInt(encrypt.length)
.put(encrypt);
signature = Base64.encodeBytes(bytes);
signature = Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
throw new IllegalStateException(e);
}

View File

@ -9,7 +9,6 @@ import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
import org.elasticsearch.cluster.metadata.RepositoryMetaData;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.settings.Settings;
@ -26,6 +25,7 @@ import org.elasticsearch.license.plugin.TestUtils;
import org.elasticsearch.test.ESTestCase;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;
@ -113,7 +113,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses");
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.encodeBytes(encrypt(contentBuilder.bytes().toBytes())));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes())));
builder.endArray();
builder.startArray("signed_licenses");
builder.endArray();
@ -143,7 +143,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses");
contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.encodeBytes(encrypt(contentBuilder.bytes().toBytes())));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes())));
builder.endArray();
builder.startArray("signed_licenses");
signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS);
@ -162,7 +162,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
builder.startArray("trial_licenses");
contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
builder.value(Base64.encodeBytes(encrypt(contentBuilder.bytes().toBytes())));
builder.value(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes())));
builder.endArray();
builder.startArray("signed_licenses");
signedLicense.toXContent(builder, ToXContent.EMPTY_PARAMS);
@ -190,7 +190,7 @@ public class LicensesMetaDataSerializationTests extends ESTestCase {
output.writeVInt(1);
XContentBuilder contentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
trialLicense.toXContent(contentBuilder, new ToXContent.MapParams(Collections.singletonMap(License.LICENSE_SPEC_VIEW_MODE, "true")));
output.writeString(Base64.encodeBytes(encrypt(contentBuilder.bytes().toBytes())));
output.writeString(Base64.getEncoder().encodeToString(encrypt(contentBuilder.bytes().toBytes())));
byte[] bytes = output.bytes().toBytes();
ByteBufferStreamInput input = new ByteBufferStreamInput(ByteBuffer.wrap(bytes));

View File

@ -9,7 +9,6 @@ import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.Version;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
@ -53,6 +52,7 @@ import java.security.AccessController;
import java.security.KeyStore;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
@ -683,7 +683,7 @@ public class HttpExporter extends Exporter {
void apply(HttpURLConnection connection) throws UnsupportedEncodingException {
String userInfo = username + ":" + (password != null ? new String(password) : "");
String basicAuth = "Basic " + Base64.encodeBytes(userInfo.getBytes("ISO-8859-1"));
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(userInfo.getBytes("ISO-8859-1"));
connection.setRequestProperty("Authorization", basicAuth);
}
}

View File

@ -7,7 +7,6 @@ package org.elasticsearch.shield.authc;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.Version;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
@ -29,6 +28,7 @@ import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportMessage;
import java.io.IOException;
import java.util.Base64;
import static org.elasticsearch.shield.Security.setting;
import static org.elasticsearch.shield.support.Exceptions.authenticationError;
@ -157,7 +157,7 @@ public class InternalAuthenticationService extends AbstractComponent implements
static User decodeUser(String text) {
try {
byte[] bytes = Base64.decode(text);
byte[] bytes = Base64.getDecoder().decode(text);
StreamInput input = StreamInput.wrap(bytes);
Version version = Version.readVersion(input);
input.setVersion(version);
@ -173,7 +173,7 @@ public class InternalAuthenticationService extends AbstractComponent implements
Version.writeVersion(Version.CURRENT, output);
User.writeTo(user, output);
byte[] bytes = output.bytes().toBytes();
return Base64.encodeBytes(bytes);
return Base64.getEncoder().encodeToString(bytes);
} catch (IOException ioe) {
if (logger != null) {
logger.error("could not encode authenticated user in message header... falling back to token headers", ioe);

View File

@ -5,13 +5,12 @@
*/
package org.elasticsearch.shield.authc.support;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.hash.MessageDigests;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Locale;
import java.util.Random;
@ -145,7 +144,7 @@ public enum Hasher {
byte[] textBytes = CharArrays.toUtf8Bytes(text.internalChars());
MessageDigest md = MessageDigests.sha1();
md.update(textBytes);
String hash = Base64.encodeBytes(md.digest());
String hash = Base64.getEncoder().encodeToString(md.digest());
return (SHA1_PREFIX + hash).toCharArray();
}
@ -158,7 +157,7 @@ public enum Hasher {
byte[] textBytes = CharArrays.toUtf8Bytes(text.internalChars());
MessageDigest md = MessageDigests.sha1();
md.update(textBytes);
String passwd64 = Base64.encodeBytes(md.digest());
String passwd64 = Base64.getEncoder().encodeToString(md.digest());
String hashNoPrefix = hashStr.substring(SHA1_PREFIX.length());
return SecuredString.constantTimeEquals(hashNoPrefix, passwd64);
}
@ -169,7 +168,7 @@ public enum Hasher {
public char[] hash(SecuredString text) {
MessageDigest md = MessageDigests.md5();
md.update(CharArrays.toUtf8Bytes(text.internalChars()));
String hash = Base64.encodeBytes(md.digest());
String hash = Base64.getEncoder().encodeToString(md.digest());
return (MD5_PREFIX + hash).toCharArray();
}
@ -182,7 +181,7 @@ public enum Hasher {
hashStr = hashStr.substring(MD5_PREFIX.length());
MessageDigest md = MessageDigests.md5();
md.update(CharArrays.toUtf8Bytes(text.internalChars()));
String computedHashStr = Base64.encodeBytes(md.digest());
String computedHashStr = Base64.getEncoder().encodeToString(md.digest());
return SecuredString.constantTimeEquals(hashStr, computedHashStr);
}
},
@ -194,7 +193,7 @@ public enum Hasher {
md.update(CharArrays.toUtf8Bytes(text.internalChars()));
char[] salt = SaltProvider.salt(8);
md.update(CharArrays.toUtf8Bytes(salt));
String hash = Base64.encodeBytes(md.digest());
String hash = Base64.getEncoder().encodeToString(md.digest());
char[] result = new char[SSHA256_PREFIX.length() + salt.length + hash.length()];
System.arraycopy(SSHA256_PREFIX.toCharArray(), 0, result, 0, SSHA256_PREFIX.length());
System.arraycopy(salt, 0, result, SSHA256_PREFIX.length(), salt.length);
@ -213,7 +212,7 @@ public enum Hasher {
MessageDigest md = MessageDigests.sha256();
md.update(CharArrays.toUtf8Bytes(text.internalChars()));
md.update(new String(saltAndHash, 0, 8).getBytes(StandardCharsets.UTF_8));
String computedHash = Base64.encodeBytes(md.digest());
String computedHash = Base64.getEncoder().encodeToString(md.digest());
return SecuredString.constantTimeEquals(computedHash, new String(saltAndHash, 8, saltAndHash.length - 8));
}
},

View File

@ -5,13 +5,12 @@
*/
package org.elasticsearch.shield.authc.support;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.shield.authc.AuthenticationToken;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import static org.elasticsearch.shield.support.Exceptions.authenticationError;
@ -85,8 +84,8 @@ public class UsernamePasswordToken implements AuthenticationToken {
char[] userpasswd;
try {
userpasswd = CharArrays.utf8BytesToChars(Base64.decode(headerValue.substring(BASIC_AUTH_PREFIX.length()).trim()));
} catch (IllegalArgumentException | IOException e) {
userpasswd = CharArrays.utf8BytesToChars(Base64.getDecoder().decode(headerValue.substring(BASIC_AUTH_PREFIX.length()).trim()));
} catch (IllegalArgumentException e) {
throw authenticationError("invalid basic authentication header encoding", e);
}
@ -109,7 +108,7 @@ public class UsernamePasswordToken implements AuthenticationToken {
chars.put(username).put(':').put(passwd.internalChars());
//TODO we still have passwords in Strings in headers
String basicToken = Base64.encodeBytes(CharArrays.toUtf8Bytes(chars.array()));
String basicToken = Base64.getEncoder().encodeToString(CharArrays.toUtf8Bytes(chars.array()));
return "Basic " + basicToken;
}
}

View File

@ -6,7 +6,6 @@
package org.elasticsearch.shield.crypto;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
@ -39,6 +38,7 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@ -138,11 +138,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
keyFile = resolveSystemKey(settings, env);
systemKey = readSystemKey(keyFile);
randomKey = generateSecretKey(RANDOM_KEY_SIZE);
try {
randomKeyBase64 = Base64.encodeBytes(randomKey.getEncoded(), 0, randomKey.getEncoded().length, Base64.URL_SAFE);
} catch (IOException e) {
throw new ElasticsearchException("failed to encode key data as base64", e);
}
randomKeyBase64 = Base64.getUrlEncoder().encodeToString(randomKey.getEncoded());
signingKey = createSigningKey(systemKey, randomKey);
@ -256,17 +252,17 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
} else {
byte[] randomKeyBytes;
try {
randomKeyBytes = Base64.decode(base64RandomKey, Base64.URL_SAFE);
if (randomKeyBytes.length * 8 != RANDOM_KEY_SIZE) {
logger.debug("incorrect random key data length. received [{}] bytes", randomKeyBytes.length);
throw new IllegalArgumentException("tampered signed text");
}
SecretKey randomKey = new SecretKeySpec(randomKeyBytes, KEY_ALGO);
signingKey = createSigningKey(systemKey, randomKey);
} catch (IOException e) {
randomKeyBytes = Base64.getUrlDecoder().decode(base64RandomKey);
} catch (IllegalArgumentException e) {
logger.error("error occurred while decoding key data", e);
throw new IllegalStateException("error while verifying the signed text");
}
if (randomKeyBytes.length * 8 != RANDOM_KEY_SIZE) {
logger.debug("incorrect random key data length. received [{}] bytes", randomKeyBytes.length);
throw new IllegalArgumentException("tampered signed text");
}
SecretKey randomKey = new SecretKeySpec(randomKeyBytes, KEY_ALGO);
signingKey = createSigningKey(systemKey, randomKey);
}
try {
@ -297,7 +293,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
}
byte[] charBytes = CharArrays.toUtf8Bytes(chars);
String base64 = Base64.encodeBytes(encryptInternal(charBytes, key));
String base64 = Base64.getEncoder().encodeToString(encryptInternal(charBytes, key));
return ENCRYPTED_TEXT_PREFIX.concat(base64).toCharArray();
}
@ -335,8 +331,8 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
String encrypted = new String(chars, ENCRYPTED_TEXT_PREFIX.length(), chars.length - ENCRYPTED_TEXT_PREFIX.length());
byte[] bytes;
try {
bytes = Base64.decode(encrypted);
} catch (IOException e) {
bytes = Base64.getDecoder().decode(encrypted);
} catch (IllegalArgumentException e) {
throw new ElasticsearchException("unable to decode encrypted data", e);
}
@ -430,7 +426,7 @@ public class InternalCryptoService extends AbstractLifecycleComponent<InternalCr
private static String signInternal(String text, SecretKey key) throws IOException {
Mac mac = createMac(key);
byte[] sig = mac.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBytes(sig, 0, sig.length, Base64.URL_SAFE);
return Base64.getUrlEncoder().encodeToString(sig);
}

View File

@ -8,7 +8,6 @@ package org.elasticsearch.shield.authc;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.Version;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
@ -37,6 +36,7 @@ import org.junit.Rule;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import static org.elasticsearch.shield.support.Exceptions.authenticationError;
@ -751,7 +751,7 @@ public class InternalAuthenticationServiceTests extends ESTestCase {
User user = new User("username", "r1", "r2", "r3");
String text = InternalAuthenticationService.encodeUser(user, null);
StreamInput input = StreamInput.wrap(Base64.decode(text));
StreamInput input = StreamInput.wrap(Base64.getDecoder().decode(text));
Version version = Version.readVersion(input);
assertThat(version, is(Version.CURRENT));
}

View File

@ -6,7 +6,6 @@
package org.elasticsearch.shield.authc.support;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.common.Base64;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.ESTestCase;
@ -14,6 +13,7 @@ import org.junit.Rule;
import org.junit.rules.ExpectedException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.elasticsearch.test.ShieldTestsUtils.assertAuthenticationException;
import static org.hamcrest.Matchers.equalTo;
@ -35,7 +35,7 @@ public class UsernamePasswordTokenTests extends ESTestCase {
assertThat(header, notNullValue());
assertTrue(header.startsWith("Basic "));
String token = header.substring("Basic ".length());
token = new String(Base64.decode(token), StandardCharsets.UTF_8);
token = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8);
int i = token.indexOf(":");
assertTrue(i > 0);
String username = token.substring(0, i);
@ -46,7 +46,7 @@ public class UsernamePasswordTokenTests extends ESTestCase {
public void testExtractToken() throws Exception {
ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
String header = "Basic " + Base64.encodeBytes("user1:test123".getBytes(StandardCharsets.UTF_8));
String header = "Basic " + Base64.getEncoder().encodeToString("user1:test123".getBytes(StandardCharsets.UTF_8));
threadContext.putHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, header);
UsernamePasswordToken token = UsernamePasswordToken.extractToken(threadContext);
assertThat(token, notNullValue());

View File

@ -5,12 +5,12 @@
*/
package org.elasticsearch.xpack.common.http.auth.basic;
import org.elasticsearch.common.Base64;
import org.elasticsearch.xpack.common.http.auth.ApplicableHttpAuth;
import org.elasticsearch.xpack.common.secret.SecretService;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
*/
@ -24,7 +24,7 @@ public class ApplicableBasicAuth extends ApplicableHttpAuth<BasicAuth> {
}
public static String headerValue(String username, char[] password) {
return "Basic " + Base64.encodeBytes((username + ":" + new String(password)).getBytes(StandardCharsets.UTF_8));
return "Basic " + Base64.getEncoder().encodeToString((username + ":" + new String(password)).getBytes(StandardCharsets.UTF_8));
}
public void apply(HttpURLConnection connection) {