-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmsService.java
More file actions
65 lines (56 loc) · 2.29 KB
/
Copy pathSmsService.java
File metadata and controls
65 lines (56 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import com.google.gson.Gson;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.LocalDateTime;
import java.util.Formatter;
@Service
public class SmsService {
private final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final String HOST="https://www.smsup.es/api/sms/";
private final String SECRET_KEY="your_key";
private final String CLIENT_ID="your_id";
/*
Send sms. Can return any type
*/
public HttpStatus sendSms(SmsEntity entity) throws Exception{
String now=LocalDateTime.now().withNano(0)+"+00:00";//GMT (London, Lisbon) used here
//Google Json serializer
Gson gson=new Gson();
String query="POST/api/sms/"+now+gson.toJson(entity);
//Add headers
HttpHeaders headers = new HttpHeaders();
headers.set("Firma", CLIENT_ID+":"+generateHMACSignature(query, SECRET_KEY));
headers.set("Sms-Date", now);
//Add body and headers to request
HttpEntity<SmsEntity> request = new HttpEntity<>(entity, headers);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(HOST, HttpMethod.POST, request, String.class).getStatusCode();
}
private String toHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
return formatter.toString();
}
/*
Generates HMAC signature to attach to headers of every request
*/
private String generateHMACSignature(String data, String key)
throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
{
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
return toHexString(mac.doFinal(data.getBytes()));
}
}