Clover icon

sunshower-core

  1. Project Clover database Fri Apr 6 2018 03:27:42 UTC
  2. Package io.sunshower.service.security.crypto

File MessageAuthenticationCode.java

 

Coverage histogram

../../../../../img/srcFileCovDistChart9.png
10% of files have more coverage

Code metrics

6
23
6
2
72
61
10
0.43
3.83
3
1.67

Classes

Class Line # Actions
MessageAuthenticationCode 11 21 8
0.903225890.3%
MessageAuthenticationCode.Algorithm 13 2 2
0.550%
 

Contributing tests

This file is covered by 9 tests. .

Source view

1    package io.sunshower.service.security.crypto;
2   
3    import io.sunshower.core.security.InvalidTokenException;
4    import java.security.InvalidKeyException;
5    import java.security.NoSuchAlgorithmException;
6    import java.util.Arrays;
7    import java.util.Base64;
8    import javax.crypto.Mac;
9    import javax.crypto.spec.SecretKeySpec;
10   
 
11    public class MessageAuthenticationCode implements Signature {
12   
 
13    public enum Algorithm {
14    MD5("HmacMD5"),
15    SHA1("HmacSHA1"),
16    SHA256("HmacSHA256");
17   
18    final String name;
19   
 
20  3 toggle private Algorithm(final String name) {
21  3 this.name = name;
22    }
23   
 
24  0 toggle public String value() {
25  0 return this.name;
26    }
27    }
28   
29    private final Mac messageCode;
30   
 
31  2 toggle public MessageAuthenticationCode(Algorithm algorithm, String secret) {
32  2 try {
33  2 this.messageCode = Mac.getInstance(algorithm.name);
34  2 this.messageCode.init(new SecretKeySpec(secret.getBytes(), algorithm.name));
35    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
36  0 throw new IllegalStateException(e);
37    }
38    }
39   
 
40  14 toggle private synchronized byte[] createKey(byte[] content) {
41  14 return this.messageCode.doFinal(content);
42    }
43   
 
44  8 toggle @Override
45    public String id(String token) {
46  8 if (token != null) {
47  8 final Base64.Decoder decoder = Base64.getDecoder();
48  8 final String[] parts = token.split(":");
49  8 if (parts.length == 2) {
50  7 final byte[] id = decoder.decode(parts[0]);
51  7 final byte[] encrypted = decoder.decode(parts[1]);
52  7 final byte[] hashedBytes = createKey(id);
53  7 if (Arrays.equals(encrypted, hashedBytes)) {
54  6 return new String(id);
55    } else {
56  1 throw new InvalidTokenException("Error: provided signature did not match.");
57    }
58    } else {
59  1 throw new InvalidTokenException("Invalid token format: '" + token + "'");
60    }
61    }
62  0 throw new InvalidTokenException("Token must not be null");
63    }
64   
 
65  7 toggle @Override
66    public String token(String input) {
67  7 final Base64.Encoder encoder = Base64.getEncoder();
68  7 final byte[] agenthash = encoder.encode(createKey(input.getBytes()));
69  7 final byte[] encodedData = encoder.encode(input.getBytes());
70  7 return new String(encodedData) + ":" + new String(agenthash);
71    }
72    }