|
| 1 | +/* |
| 2 | +* Copyright 2021 Google LLC |
| 3 | +* |
| 4 | +* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | +* in compliance with the License. You may obtain a copy of the License at |
| 6 | +* |
| 7 | +* http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +* |
| 9 | +* Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | +* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | +* or implied. See the License for the specific language governing permissions and limitations under |
| 12 | +* the License. |
| 13 | +*/ |
| 14 | + |
| 15 | +package com.google.api.client.auth.oauth; |
| 16 | + |
| 17 | +import com.google.api.client.util.StringUtils; |
| 18 | +import com.google.common.io.BaseEncoding; |
| 19 | +import java.security.GeneralSecurityException; |
| 20 | +import javax.crypto.Mac; |
| 21 | +import javax.crypto.SecretKey; |
| 22 | +import javax.crypto.spec.SecretKeySpec; |
| 23 | + |
| 24 | +/** OAuth {@code "HMAC-SHA256"} signature method. */ |
| 25 | +public final class OAuthHmacSha256Signer implements OAuthSigner { |
| 26 | + |
| 27 | +/** Client secret */ |
| 28 | +private final String clientSharedSecret; |
| 29 | + |
| 30 | +/** Token secret */ |
| 31 | +private String tokenSharedSecret; |
| 32 | + |
| 33 | +public void setTokenSecret(String tokenSecret) { |
| 34 | +tokenSharedSecret = tokenSecret; |
| 35 | +} |
| 36 | + |
| 37 | +public OAuthHmacSha256Signer(String clientSecret) { |
| 38 | +this.clientSharedSecret = clientSecret; |
| 39 | +} |
| 40 | + |
| 41 | +@Override |
| 42 | +public String getSignatureMethod() { |
| 43 | +return "HMAC-SHA256"; |
| 44 | +} |
| 45 | + |
| 46 | +@Override |
| 47 | +public String computeSignature(String signatureBaseString) throws GeneralSecurityException { |
| 48 | +// compute key |
| 49 | +StringBuilder keyBuffer = new StringBuilder(); |
| 50 | +if (clientSharedSecret != null) { |
| 51 | +keyBuffer.append(OAuthParameters.escape(clientSharedSecret)); |
| 52 | +} |
| 53 | +keyBuffer.append('&'); |
| 54 | +if (tokenSharedSecret != null) { |
| 55 | +keyBuffer.append(OAuthParameters.escape(tokenSharedSecret)); |
| 56 | +} |
| 57 | +String key = keyBuffer.toString(); |
| 58 | +// sign |
| 59 | +SecretKey secretKey = new SecretKeySpec(StringUtils.getBytesUtf8(key), "HmacSHA256"); |
| 60 | +Mac mac = Mac.getInstance("HmacSHA256"); |
| 61 | +mac.init(secretKey); |
| 62 | +return BaseEncoding.base64().encode(mac.doFinal(StringUtils.getBytesUtf8(signatureBaseString))); |
| 63 | +} |
| 64 | +} |
0 commit comments