|
1 | 1 | package com.pubnub.api.core; |
2 | 2 |
|
| 3 | +import com.pubnub.api.core.utils.Base64; |
| 4 | + |
| 5 | +import javax.crypto.Mac; |
| 6 | +import javax.crypto.spec.SecretKeySpec; |
3 | 7 | import java.io.UnsupportedEncodingException; |
4 | 8 | import java.net.URLEncoder; |
| 9 | +import java.security.InvalidKeyException; |
| 10 | +import java.security.NoSuchAlgorithmException; |
5 | 11 | import java.util.List; |
6 | 12 | import java.util.Map; |
7 | 13 | import java.util.Set; |
@@ -86,4 +92,30 @@ public static String preparePamArguments(Map<String, String> pamArgs){ |
86 | 92 | return stringifiedArguments; |
87 | 93 | } |
88 | 94 |
|
| 95 | + public static String signSHA256(final String key, final String data) throws PubnubException { |
| 96 | + Mac sha256HMAC; |
| 97 | + byte[] hmacData; |
| 98 | + SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "HmacSHA256"); |
| 99 | + |
| 100 | + try { |
| 101 | + sha256HMAC = Mac.getInstance("HmacSHA256"); |
| 102 | + } catch (NoSuchAlgorithmException e) { |
| 103 | + throw PubnubException.builder().pubnubError(PubnubError.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build(); |
| 104 | + } |
| 105 | + |
| 106 | + try { |
| 107 | + sha256HMAC.init(secretKey); |
| 108 | + } catch (InvalidKeyException e) { |
| 109 | + throw PubnubException.builder().pubnubError(PubnubError.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build(); |
| 110 | + } |
| 111 | + |
| 112 | + try { |
| 113 | + hmacData = sha256HMAC.doFinal(data.getBytes("UTF-8")); |
| 114 | + } catch (UnsupportedEncodingException e) { |
| 115 | + throw PubnubException.builder().pubnubError(PubnubError.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build(); |
| 116 | + } |
| 117 | + |
| 118 | + return new String(Base64.encode(hmacData, 0)).replace('+', '-').replace('/', '_'); |
| 119 | + } |
| 120 | + |
89 | 121 | } |
0 commit comments