HADOOP-15235. Authentication Tokens should use HMAC instead of MAC (rkanter)

This commit is contained in:
Robert Kanter 2018-02-20 17:24:37 -08:00
parent 84cea0011f
commit 324e5a7cf2

View File

@ -14,8 +14,11 @@
package org.apache.hadoop.security.authentication.util; package org.apache.hadoop.security.authentication.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import java.nio.charset.Charset; import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -24,6 +27,7 @@
*/ */
public class Signer { public class Signer {
private static final String SIGNATURE = "&s="; private static final String SIGNATURE = "&s=";
private static final String SIGNING_ALGORITHM = "HmacSHA256";
private SignerSecretProvider secretProvider; private SignerSecretProvider secretProvider;
@ -86,25 +90,27 @@ public String verifyAndExtract(String signedStr) throws SignerException {
*/ */
protected String computeSignature(byte[] secret, String str) { protected String computeSignature(byte[] secret, String str) {
try { try {
MessageDigest md = MessageDigest.getInstance("SHA"); SecretKeySpec key = new SecretKeySpec((secret), SIGNING_ALGORITHM);
md.update(str.getBytes(Charset.forName("UTF-8"))); Mac mac = Mac.getInstance(SIGNING_ALGORITHM);
md.update(secret); mac.init(key);
byte[] digest = md.digest(); byte[] sig = mac.doFinal(StringUtils.getBytesUtf8(str));
return new Base64(0).encodeToString(digest); return new Base64(0).encodeToString(sig);
} catch (NoSuchAlgorithmException ex) { } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
throw new RuntimeException("It should not happen, " + ex.getMessage(), ex); throw new RuntimeException("It should not happen, " + ex.getMessage(), ex);
} }
} }
protected void checkSignatures(String rawValue, String originalSignature) protected void checkSignatures(String rawValue, String originalSignature)
throws SignerException { throws SignerException {
byte[] orginalSignatureBytes = StringUtils.getBytesUtf8(originalSignature);
boolean isValid = false; boolean isValid = false;
byte[][] secrets = secretProvider.getAllSecrets(); byte[][] secrets = secretProvider.getAllSecrets();
for (int i = 0; i < secrets.length; i++) { for (int i = 0; i < secrets.length; i++) {
byte[] secret = secrets[i]; byte[] secret = secrets[i];
if (secret != null) { if (secret != null) {
String currentSignature = computeSignature(secret, rawValue); String currentSignature = computeSignature(secret, rawValue);
if (originalSignature.equals(currentSignature)) { if (MessageDigest.isEqual(orginalSignatureBytes,
StringUtils.getBytesUtf8(currentSignature))) {
isValid = true; isValid = true;
break; break;
} }