131 lines
3.5 KiB
Java

package dslab;
import dslab.exception.MissingInputException;
import dslab.util.Keys;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.stream.Collectors;
public class Message {
private ArrayList<Email> to = new ArrayList<>();
private Email from;
private String subject = "";
private String data = "";
private String hash = "";
private Integer id;
public Message() {
}
public Message(ArrayList<Email> to, Email from, String subject, String data, String hash) {
this.to = to;
this.from = from;
this.subject = subject;
this.data = data;
this.hash = hash;
}
public void allFieldsSet() throws MissingInputException {
if (this.subject == null) this.subject = "";
if (this.data == null) this.data = "";
if (this.to.isEmpty()) throw new MissingInputException("error no receiver");
if (this.from == null) throw new MissingInputException("error no sender");
}
public void addTo(Email email) {
to.add(email);
}
public String printTo() {
if (this.to.isEmpty())
return null;
return this.to.stream().map(Object::toString).collect(Collectors.joining(","));
}
public ArrayList<Email> getTo() {
return to;
}
public void setTo(ArrayList<Email> to) {
this.to = to;
}
public Email getFrom() {
return from;
}
public void setFrom(Email from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
/**
* Calculate a HMAC hash of the message.
*
* @return A Base64 encoded hash of the message.
* @throws IOException Thrown if the HMAC key (in "keys/hmac.key") cannot be found.
* @throws NoSuchAlgorithmException Thrown if HmacSHA256 is not known.
* @throws InvalidKeyException Thrown if the key is not valid.
*/
public String calculateHash() throws IOException, NoSuchAlgorithmException, InvalidKeyException {
byte[] hashFormat = String.join("\n", getFrom().toString(), printTo(), getSubject(), getData())
.getBytes(StandardCharsets.UTF_8);
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec hmac = Keys.readSecretKey(new File("keys/hmac.key"));
mac.init(hmac);
return (Base64.getEncoder().encodeToString(mac.doFinal(hashFormat)));
}
public String listMessage() {
return getId() + " " + getFrom() + " " + getSubject();
}
@Override
public String toString() {
return "from " + getFrom().toString() + "\n" +
"to " + printTo() + "\n" +
"subject " + getSubject() + "\n" +
"data " + getData() + "\n" +
"hash " + getHash() + "\n";
}
}