0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019 package org.apache.hive.service;
0020
0021 import java.security.MessageDigest;
0022 import java.security.NoSuchAlgorithmException;
0023
0024 import org.apache.commons.codec.binary.Base64;
0025 import org.slf4j.Logger;
0026 import org.slf4j.LoggerFactory;
0027
0028
0029
0030
0031
0032
0033 public class CookieSigner {
0034 private static final String SIGNATURE = "&s=";
0035 private static final String SHA_STRING = "SHA-256";
0036 private byte[] secretBytes;
0037 private static final Logger LOG = LoggerFactory.getLogger(CookieSigner.class);
0038
0039
0040
0041
0042
0043 public CookieSigner(byte[] secret) {
0044 if (secret == null) {
0045 throw new IllegalArgumentException(" NULL Secret Bytes");
0046 }
0047 this.secretBytes = secret.clone();
0048 }
0049
0050
0051
0052
0053
0054
0055 public String signCookie(String str) {
0056 if (str == null || str.isEmpty()) {
0057 throw new IllegalArgumentException("NULL or empty string to sign");
0058 }
0059 String signature = getSignature(str);
0060
0061 if (LOG.isDebugEnabled()) {
0062 LOG.debug("Signature generated for " + str + " is " + signature);
0063 }
0064 return str + SIGNATURE + signature;
0065 }
0066
0067
0068
0069
0070
0071
0072 public String verifyAndExtract(String signedStr) {
0073 int index = signedStr.lastIndexOf(SIGNATURE);
0074 if (index == -1) {
0075 throw new IllegalArgumentException("Invalid input sign: " + signedStr);
0076 }
0077 String originalSignature = signedStr.substring(index + SIGNATURE.length());
0078 String rawValue = signedStr.substring(0, index);
0079 String currentSignature = getSignature(rawValue);
0080
0081 if (LOG.isDebugEnabled()) {
0082 LOG.debug("Signature generated for " + rawValue + " inside verify is " + currentSignature);
0083 }
0084 if (!MessageDigest.isEqual(originalSignature.getBytes(), currentSignature.getBytes())) {
0085 throw new IllegalArgumentException("Invalid sign, original = " + originalSignature +
0086 " current = " + currentSignature);
0087 }
0088 return rawValue;
0089 }
0090
0091
0092
0093
0094
0095
0096 private String getSignature(String str) {
0097 try {
0098 MessageDigest md = MessageDigest.getInstance(SHA_STRING);
0099 md.update(str.getBytes());
0100 md.update(secretBytes);
0101 byte[] digest = md.digest();
0102 return new Base64(0).encodeToString(digest);
0103 } catch (NoSuchAlgorithmException ex) {
0104 throw new RuntimeException("Invalid SHA digest String: " + SHA_STRING +
0105 " " + ex.getMessage(), ex);
0106 }
0107 }
0108 }