SmsAccessToken.java
2.41 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
package com.diligrp.assistant.sms.domain;
import com.diligrp.assistant.shared.Constants;
import com.diligrp.assistant.shared.ErrorCode;
import com.diligrp.assistant.shared.codec.StringCodec;
import com.diligrp.assistant.sms.exception.SmsServiceException;
import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Base64;
import java.util.StringTokenizer;
public class SmsAccessToken implements Serializable {
private String token;
public SmsAccessToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public String toString(PrivateKey privateKey) {
try {
byte[] bytes = StringCodec.getEncoder().encode(token);
Signature signature = Signature.getInstance(Constants.SIGN_ALGORITHM);
signature.initSign(privateKey, new SecureRandom());
signature.update(bytes);
byte[] sign = signature.sign();
return String.format("%s.%s", Base64.getEncoder().encodeToString(bytes), Base64.getEncoder().encodeToString(sign));
} catch (Exception ex) {
throw new SmsServiceException(ErrorCode.ILLEGAL_ARGUMENT_ERROR, "accessToken sign failed");
}
}
public static SmsAccessToken of(String authorization, PublicKey publicKey) {
StringTokenizer tokenizer = new StringTokenizer(authorization, ".");
if (tokenizer.countTokens() != 2) {
throw new SmsServiceException(ErrorCode.ILLEGAL_ARGUMENT_ERROR, "Invalid accessToken format");
}
byte[] data = Base64.getDecoder().decode(tokenizer.nextToken());
byte[] sign = Base64.getDecoder().decode(tokenizer.nextToken());
try {
Signature signature = Signature.getInstance(Constants.SIGN_ALGORITHM);
signature.initVerify(publicKey);
signature.update(data);
boolean result = signature.verify(sign);
if (!result) {
throw new SmsServiceException(ErrorCode.UNAUTHORIZED_ACCESS_ERROR, ErrorCode.MESSAGE_ACCESS_DENIED);
}
String token = StringCodec.getDecoder().decode(data);
return new SmsAccessToken(token);
} catch (Exception ex) {
throw new SmsServiceException(ErrorCode.ILLEGAL_ARGUMENT_ERROR, "Invalid accessToken data");
}
}
}