Skip to content

Instantly share code, notes, and snippets.

@CameronBarnes
Created September 2, 2020 05:35
Show Gist options
  • Save CameronBarnes/71f9ca9eb69b294f3d8563f47dac391e to your computer and use it in GitHub Desktop.
Save CameronBarnes/71f9ca9eb69b294f3d8563f47dac391e to your computer and use it in GitHub Desktop.
Core Components for Aranea Bug Tracker
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cameronbarnes</groupId>
<artifactId>AraneaCore</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations-java5</artifactId>
<version>20.1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
package com.cameronbarnes.AraneaCore.bugtracking;
import com.cameronbarnes.AraneaCore.communication.Comment;
import com.cameronbarnes.AraneaCore.util.IDManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.time.LocalDateTime;
import java.util.ArrayList;
public class Issue {
private static Logger log = LogManager.getLogger(Issue.class.getName());
public static final String[] mTableCategories = new String[]{"issue.id",
"issue.severity",
"issue.type",
"issue.status",
"issue.createdDate",
"issue.updatedDate",
"issue.assignedDev",
"issue.category",
"issue.summary",
"issue.isPrivate"
};
private int ID;
private int mAssignedDeveloperID;
private Type mType;
private Severity mSeverity;
private Status mStatus;
private ArrayList<String> mCategory;
private boolean mPrivate = false;
private LocalDateTime mCreated;
private LocalDateTime mUpdated;
private String mSummary;
private ArrayList<Comment> mComments;
public Issue(int id, int devID, Type type, Severity severity, Status status, ArrayList<String> category, LocalDateTime created, LocalDateTime updated, String summary, ArrayList<Comment> comments, boolean aPrivate) {
ID = id;
mAssignedDeveloperID = devID;
mType = type;
mSeverity = severity;
mStatus = status;
mPrivate = aPrivate;
mCreated = created;
mUpdated = updated;
mSummary = summary;
mComments = comments;
mCategory = category;
}
public static Issue createIssue(Type type, Severity severity, ArrayList<String> category, String summary, boolean aPrivate) {
return new Issue(IDManager.getNewID(), 0, type, severity, Status.New, category, LocalDateTime.now(), LocalDateTime.now(), summary, new ArrayList<Comment>(), aPrivate);
}
public int getID() {
return ID;
}
public int getAssignedDeveloperID() {
return mAssignedDeveloperID;
}
public void setAssignedDeveloperID(int assignedDeveloperID) {
mAssignedDeveloperID = assignedDeveloperID;
if (assignedDeveloperID != 0) {
mStatus = Status.Assigned;
}
}
public Type getType() {
return mType;
}
public void setType(Type type) {
mType = type;
}
public Severity getSeverity() {
return mSeverity;
}
public void setSeverity(Severity severity) {
mSeverity = severity;
}
public Status getStatus() {
return mStatus;
}
public void setStatus(Status status) {
if (status == Status.Assigned && mAssignedDeveloperID == 0) {
log.error("Setting status to assigned but no developer has been assigned");
}
mStatus = status;
}
public ArrayList<String> getCategory() {
return (ArrayList<String>) mCategory.clone();
}
public void setCategory(ArrayList<String> category) {
mCategory = category;
}
public void addCategory(String s) {
mCategory.add(s);
}
public void removeCategory(String s) {
mCategory.remove(s);
}
public boolean isPrivate() {
return mPrivate;
}
public void setPrivate(boolean aPrivate) {
mPrivate = aPrivate;
}
public LocalDateTime getCreated() {
return mCreated;
}
public LocalDateTime getUpdated() {
return mUpdated;
}
public void setUpdated() {
mUpdated = LocalDateTime.now();
}
public String getSummary() {
return mSummary;
}
public void setSummary(String summary) {
mSummary = summary;
}
public ArrayList<Comment> getComments() {
return (ArrayList<Comment>) mComments.clone();
}
public void setComments(ArrayList<Comment> comments) {
mComments = comments;
}
public void addComment(Comment comment) {
mComments.add(comment);
}
public void removeComment(Comment comment) {
mComments.remove(comment);
}
public enum Type {
Bug,
Feature,
Enhancement
}
public enum Severity {
Minor,
Serious,
Critical
}
public enum Status {
New,
Acknowledged,
Assigned,
Resolved
}
}
package com.cameronbarnes.AraneaCore.communication;
import java.time.LocalDateTime;
public class Comment {
private LocalDateTime mDate;
private int mUserID;
private String mComment;
}
package com.cameronbarnes.AraneaCore.crypto;
public class CredentialHandling {
}
package com.cameronbarnes.AraneaCore.crypto.credentials;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Arrays;
public class Password {
private char[] mPassword;
private boolean mIsCleared;
public Password(char[] pass) {
mPassword = pass;
mIsCleared = false;
}
public char[] getValue() {
return mPassword;
}
public boolean checkValue(char[] chars) {
return Arrays.equals(chars, mPassword);
}
public String getString() {
return Arrays.toString(mPassword);
}
public void setPassword(char[] chars) {
clear();
mPassword = chars;
mIsCleared = false;
}
public void clear() {
mPassword = RandomStringUtils.randomAlphanumeric(mPassword.length).toCharArray();
System.gc();
mIsCleared = true;
}
public boolean isCleared() {
return mIsCleared;
}
@Override
public boolean equals(Object o) {
if (o.getClass() == Password.class) {
return ((Password) o).checkValue(mPassword);
}
return false;
}
}
package com.cameronbarnes.AraneaCore.crypto.credentials;
import java.util.HashMap;
import java.util.Map;
public class Permissions {
private HashMap<String, PermissionSet> mPermissions;
public Map<String, PermissionSet> getPermissions() {
return mPermissions;
}
public class PermissionSet {
}
}
package com.cameronbarnes.AraneaCore.crypto.credentials;
import org.apache.commons.lang3.RandomStringUtils;
import org.jetbrains.annotations.NotNull;
public class UsernamePasswordCredential {
private String mUsername;
private Password mPassword;
private boolean mIsCleared;
public UsernamePasswordCredential(String username, Password password) {
mUsername = username;
mPassword = password;
mIsCleared = false;
}
public void setUsername(String username) {
mUsername = username;
}
public void setPassword(Password password) {
mPassword.clear();
mPassword = password;
}
public Password getPassword() {
return mPassword;
}
public boolean isCleared() {
if (mPassword.isCleared()) {
return mIsCleared;
}
return false;
}
public void clear() {
mUsername = RandomStringUtils.randomAlphanumeric(mUsername.length());
mPassword.clear();
}
public boolean compareValues(@NotNull UsernamePasswordCredential credential) {
if (credential.mUsername.equals(mUsername)) {
return credential.mPassword.equals(mPassword);
}
return false;
}
@Override
public boolean equals(Object o) {
if (o.getClass() == UsernamePasswordCredential.class) {
if (((UsernamePasswordCredential) o).mUsername.equals(mUsername)) {
return ((UsernamePasswordCredential) o).mPassword.equals(mPassword);
}
}
return false;
}
}
package com.cameronbarnes.AraneaCore.crypto;
import com.cameronbarnes.AraneaCore.networking.NetworkData;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import javax.crypto.*;
import java.security.*;
import java.util.UUID;
public class Crypto {
public static final int SYMMETRIC_KEY_SIZE = 128;
public static final int ASYMMETRIC_KEY_SIZE = 1024;
public static final String SYMMETRIC_ALGORITHM = "AES";
public static final String ASYMMETRIC_ALGORITHM = "RSA";
public static final String ASYMMETRIC_ALGORITHM_FORMATTING = "RSA/None/OAEPWithSHA1AndMGF1Padding";
public static final String SYMMETRIC_ALGORITHM_FORMATTING = "AES/CBC/PKCS5Padding";
private UUID mUUID = null;
private SecretKey mAESKey;
private PublicKey mRemotePublicKey;
private KeyPair mKeyPair;
private final boolean mIsServer;
private KeyPairGenerator mKeyPairGenerator;
private KeyGenerator mAESKeyGenerator;
public static final SecureRandom secureRandom = new SecureRandom();
private Cipher mRSAEncryptCipher;
private Cipher mRSADecryptCipher;
private Cipher mAESEncryptCipher;
private Cipher mAESDecryptCipher;
public Crypto(KeyPair localKeys, PublicKey remotePublicKey, boolean isServer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
mKeyPair = localKeys;
mRemotePublicKey = remotePublicKey;
mIsServer = isServer;
mRSAEncryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
mRSAEncryptCipher.init(Cipher.ENCRYPT_MODE, mKeyPair.getPrivate());
mRSADecryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
mRSADecryptCipher.init(Cipher.DECRYPT_MODE, remotePublicKey);
if (isServer) {
mAESKeyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
mAESKeyGenerator.init(SYMMETRIC_KEY_SIZE, secureRandom);
}
updateAESKey(null);
}
public Crypto(KeyPair localKeys, boolean isServer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
mKeyPair = localKeys;
mIsServer = isServer;
mRSAEncryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
mRSAEncryptCipher.init(Cipher.ENCRYPT_MODE, mKeyPair.getPrivate());
mRSADecryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
if (isServer) {
mAESKeyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
mAESKeyGenerator.init(SYMMETRIC_KEY_SIZE, secureRandom);
}
updateAESKey(null);
}
public Crypto(boolean isServer) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
mIsServer = isServer;
mKeyPairGenerator = KeyPairGenerator.getInstance(ASYMMETRIC_ALGORITHM);
mKeyPairGenerator.initialize(ASYMMETRIC_KEY_SIZE, secureRandom);
mKeyPair = genRSAKey();
mRSAEncryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
mRSAEncryptCipher.init(Cipher.ENCRYPT_MODE, mKeyPair.getPrivate());
mRSADecryptCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM_FORMATTING);
if (isServer) {
mAESKeyGenerator = KeyGenerator.getInstance(SYMMETRIC_ALGORITHM);
mAESKeyGenerator.init(SYMMETRIC_KEY_SIZE, secureRandom);
}
updateAESKey(null);
}
public void updateAESKey(SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
if (isServer()) {
if (key == null) {
mAESKey = genAESKey();
}
else {
mAESKey = key;
}
}
else {
mAESKey = key;
}
if (mAESKey != null) {
mAESEncryptCipher = Cipher.getInstance(SYMMETRIC_ALGORITHM_FORMATTING);
mAESEncryptCipher.init(Cipher.ENCRYPT_MODE, mAESKey);
mAESDecryptCipher = Cipher.getInstance(SYMMETRIC_ALGORITHM_FORMATTING);
mAESDecryptCipher.init(Cipher.DECRYPT_MODE, mAESKey);
}
}
public NetworkData decryptNetworkData(@NotNull NetworkData networkData, boolean symmetric) throws BadPaddingException, IllegalBlockSizeException {
byte[] rawBytes = networkData.getByteData();
byte[] bytes;
if (symmetric) {
bytes = decryptBytesAES(rawBytes);
}
else {
bytes = decryptBytesRSA(rawBytes);
}
return NetworkData.deserializeFromBytes(bytes);
}
public NetworkData encryptNetworkData(@NotNull NetworkData networkData, boolean symmetric) throws BadPaddingException, IllegalBlockSizeException {
if (mUUID != null && networkData.getUUID() == null) {
networkData.setUUID(mUUID);
}
byte[] rawBytes = networkData.serializeToBytes();
byte[] encryptedBytes;
if (symmetric) {
encryptedBytes = encryptBytesAES(rawBytes);
}
else {
encryptedBytes = encryptBytesRSA(rawBytes);
}
NetworkData data =
new NetworkData(NetworkData.DataType.EncryptedNetworkDataRSA, mUUID);
data.setByteData(encryptedBytes);
return data;
}
public byte[] decryptBytesRSA(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
return mRSADecryptCipher.doFinal(bytes);
}
public byte[] encryptBytesRSA(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
return mRSAEncryptCipher.doFinal(bytes);
}
public byte[] decryptBytesAES(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
return mAESDecryptCipher.doFinal(bytes);
}
public byte[] encryptBytesAES(byte[] bytes) throws BadPaddingException, IllegalBlockSizeException {
return mAESEncryptCipher.doFinal(bytes);
}
/**
*
* @param key the crypto key to set
*
* sets the value of the AES key and initialize the AES ciphers to use it
*/
public void setAESKey(SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
updateAESKey(key);
}
/**
*
* @param key the crypto key to set
*
* sets the value of the remote key and initialize the RSA decryption cipher to use it
*/
public void setRemotePublicKey(PublicKey key) throws InvalidKeyException {
mRemotePublicKey = key;
mRSADecryptCipher.init(Cipher.DECRYPT_MODE, key);
}
public SecretKey getAESKey() {
return mAESKey;
}
public PublicKey getPublicKey() {
return mKeyPair.getPublic();
}
public PublicKey getRemotePublicKey() {
return mRemotePublicKey;
}
public boolean isServer() {
return mIsServer;
}
public void genUUID() {
mUUID = UUID.randomUUID();
}
public boolean checkUUID(UUID uuid) {
return mUUID.equals(uuid);
}
@NotNull
@Contract(pure = true)
public KeyPair genRSAKey() {
return mKeyPairGenerator.generateKeyPair();
}
@NotNull
@Contract(pure = true)
public SecretKey genAESKey() {
return mAESKeyGenerator.generateKey();
}
}
package com.cameronbarnes.AraneaCore.database;
import com.cameronbarnes.AraneaCore.crypto.credentials.UsernamePasswordCredential;
import com.sun.istack.internal.NotNull;
import org.bson.Document;
import org.jetbrains.annotations.Contract;
import java.util.UUID;
public class DatabasePacket {
private final UUID mUUID;
private final boolean mIsRequest;
private final PacketType mPacketType;
private final DatabaseResponse mResponse;
private String mProjectName;
private UsernamePasswordCredential mCredential;
private Document mDocument;
private DatabasePacket(String projectName, boolean isRequest, PacketType type, DatabaseResponse response, UUID uuid) {
mUUID = uuid;
mIsRequest = isRequest;
mPacketType = type;
mResponse = response;
mProjectName = projectName;
}
@NotNull
@Contract(value = "_, _, _ -> new", pure = true)
public static DatabasePacket newRequest(String projectName, PacketType type, UUID uuid) {
return new DatabasePacket(projectName, true, type, null, uuid);
}
@NotNull
@Contract(value = "_, _, _, _ -> new", pure = true)
public static DatabasePacket newResponse(String projectName, PacketType type, DatabaseResponse response, UUID uuid) {
return new DatabasePacket(projectName, false, type, response, uuid);
}
@NotNull
@Contract(value = "_, _, _ -> new")
public static DatabasePacket credentialVerificationRequest(String projectName, UsernamePasswordCredential credential, UUID uuid) {
DatabasePacket packet = newRequest(projectName, PacketType.ProcessCredentials, uuid);
packet.mCredential = credential;
return packet;
}
public String getProjectName() {
return mProjectName;
}
public Document getDocument() {
return mDocument;
}
public void setDocument(Document document) {
mDocument = document;
}
public UsernamePasswordCredential getCredential() {
return mCredential;
}
public PacketType getPacketType() {
return mPacketType;
}
public DatabaseResponse getResponse() {
return mResponse;
}
public boolean isRequest() {
return mIsRequest;
}
public enum PacketType {
AddUser,
ProcessCredentials,
RequestUserData,
RequestDocument,
RequestIndex
}
public enum DatabaseResponse {
Success,
GenericFailure,
NoSuchDocument,
InvalidPermissions,
NoSuchUser,
AuthenticationError
}
public static class PacketResponseTypeMismatchException extends Exception {
public PacketResponseTypeMismatchException(boolean expectedRequest) {
super(expectedRequest ? "Expected request packet, received response" :
"Expected response packet, received request");
}
}
}
package com.cameronbarnes.AraneaCore.logging;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Order;
import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import java.net.URI;
@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY)
@Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {
static Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {
builder.setConfigurationName(name);
builder.setStatusLevel(Level.ERROR);
builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL).
addAttribute("level", Level.DEBUG));
AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").
addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern",
"%c{3} %M %d{dd MMM yyyy HH:mm:ss} %highlight{%-5p [%t]: %m%n}{STYLE=Logback}").addAttribute("disableAnsi", "false"));
appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
builder.add(appenderBuilder);
builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).
add(builder.newAppenderRef("Stdout")).
addAttribute("additivity", false));
builder.add(builder.newRootLogger(Level.TRACE).add(builder.newAppenderRef("Stdout")));
return builder.build();
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
return getConfiguration(loggerContext, source.toString(), null);
}
@Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
return createConfiguration(name, builder);
}
@Override
protected String[] getSupportedTypes() {
return new String[] {"*"};
}
}
package com.cameronbarnes.AraneaCore.networking;
import com.cameronbarnes.AraneaCore.crypto.credentials.UsernamePasswordCredential;
import com.cameronbarnes.AraneaCore.database.DatabasePacket;
import com.cameronbarnes.AraneaCore.database.DatabasePacket.DatabaseResponse;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.SecretKey;
import java.io.*;
import java.security.Key;
import java.security.PublicKey;
import java.util.UUID;
public class NetworkData implements Serializable {
private UUID mUUID;
private DataType mDataType;
//Data types begin here
private byte[] byteData = null;
private String stringData = null;
private String mProjectName;
private int intData = 0;
private PublicKey mPublicKey;
private SecretKey mSecretKey;
private Key mKey;
private UsernamePasswordCredential mCredential;
private static final Logger log = LoggerFactory.getLogger(NetworkData.class.getName());
public NetworkData(DataType type, UUID uuid) {
mUUID = uuid;
mDataType = type;
}
public UUID getUUID() {
return mUUID;
}
public void setUUID(UUID uuid) {
mUUID = uuid;
}
public DataType getDataType() {
return mDataType;
}
public byte[] getByteData() {
return byteData;
}
public void setByteData(byte[] byteData) {
this.byteData = byteData;
}
public String getStringData() {
return stringData;
}
public void setStringData(String stringData) {
this.stringData = stringData;
}
public String getProjectName() {
return mProjectName;
}
public void setProjectName(String projectName) {
mProjectName = projectName;
}
public int getIntData() {
return intData;
}
public void setIntData(int intData) {
this.intData = intData;
}
public SecretKey getSecretKey() {
return mSecretKey;
}
public void setSecretKey(SecretKey secretKey) {
mSecretKey = secretKey;
}
public PublicKey getPublicKey() {
return mPublicKey;
}
public void setPublicKey(PublicKey publicKey) {
mPublicKey = publicKey;
}
public Key getKey() {
return mKey;
}
public void setKey(Key key) {
mKey = key;
}
public UsernamePasswordCredential getCredential() {
return mCredential;
}
public void setCredential(UsernamePasswordCredential credential) {
if (mCredential != null) {
mCredential.clear();
}
mCredential = credential;
}
@NotNull
@Contract(value = "_ -> new", pure = true)
public static NetworkData RSAKeyRequest(PublicKey localPublicKey) {
NetworkData data = new NetworkData(DataType.RSAKeyRequest, null);
data.setPublicKey(localPublicKey);
return data;
}
@NotNull
@Contract(value = "_ -> new", pure = true)
public static NetworkData RSAKeyResponse(PublicKey localPublicKey) {
NetworkData data = new NetworkData(DataType.RSAKeyResponse, null);
data.setPublicKey(localPublicKey);
return data;
}
@NotNull
@Contract(value = "_ -> new", pure = true)
public static NetworkData invalidKeyError(Key key) {
NetworkData data = new NetworkData(DataType.InvalidKeyError, null);
data.setKey(key);
return data;
}
@Contract(value = "_-> new", pure = true)
public static NetworkData newError(@NotNull DatabasePacket.DatabaseResponse type) {
NetworkData data = null;
switch (type) {
case GenericFailure:
case NoSuchDocument:
case InvalidPermissions:
case NoSuchUser:
case AuthenticationError:
data = new NetworkData(DataType.DatabaseResponseError, null);
data.setStringData(type.toString());
break;
case Success:
log.error("Success is not a valid error type");
default:
data = new NetworkData(DataType.ErrorError, null);
break;
}
return data;
}
@NotNull
@Contract(value = "_ -> new", pure = true)
public static NetworkData issueAESKey(SecretKey AESKey) {
NetworkData data = new NetworkData(DataType.IssueAESKey, null);
data.setSecretKey(AESKey);
return data;
}
@NotNull
@Contract(value = " -> new", pure = true)
public static NetworkData AESKeyResponse() {
return new NetworkData(DataType.AESKeyResponse, null);
}
public byte[] serializeToBytes() {
byte[] bytes = null;
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bOut);
out.writeObject(this);
out.flush();
bytes = bOut.toByteArray();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (out != null) out.close();
bOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
public static NetworkData deserializeFromBytes(byte[] bytes) {
NetworkData data = null;
ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
ObjectInputStream in = null;
try {
in = new ObjectInputStream(bIn);
data = (NetworkData) in.readObject();
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
finally {
try {
if (in != null) in.close();
bIn.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
public enum DataType {
RSAKeyRequest,
RSAKeyResponse,
IssueAESKey,
AESKeyResponse,
CredentialRequest,
CredentialResponse,
EncryptedNetworkDataRSA,
EncryptedNetworkDataAES,
DocumentRequest,
DocumentResponse,
DocumentUpdateRequest,
DocumentUpdateResponse,
//Errors
InvalidKeyError,
InvalidUUIDError,
InvalidCredentialError,
ExpectedEncryptedError,
DatabaseResponseError,
ErrorError
}
}
package com.cameronbarnes.AraneaCore.usermanagment;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class User {
private int ID;
private Role mRole;
private String mEmail;
private HashMap<String, String> mOtherContactInformation; //Contact type/Value
public User(int id, String email, HashMap<String, String> otherContactInformation, Role role) {
ID = id;
mRole = role;
mEmail = email;
mOtherContactInformation = otherContactInformation;
}
@NotNull
@Contract(" -> new")
public static User getAnon() {
return new User(0, "", new HashMap<>(), Role.Anon);
}
public int getID() {
return ID;
}
public Role getRole() {
return mRole;
}
public void setRole(Role role) {
mRole = role;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
public Map<String, String> getOtherContactInformation() {
return mOtherContactInformation;
}
public void setOtherContactInformation(HashMap<String, String> otherContactInformation) {
mOtherContactInformation = otherContactInformation;
}
public void removeContactInformation(String key) {
mOtherContactInformation.remove(key);
}
public void addContactInformation(String key, String value) {
mOtherContactInformation.put(key, value);
}
public enum Role {
User,
Developer,
ProjectManager,
Admin,
Anon
}
}
package com.cameronbarnes.AraneaCore.util;
import java.util.Random;
public class IDManager {
public static int getNewID() {
return new Random().nextInt((999999 - 1) + 1) + 1; //TODO actually make this class function
}
}
package com.cameronbarnes.AraneaCore.util;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.ResourceBundle;
public class Utils {
@NotNull
@Contract(pure = true)
public static String[] getStringsFromKeyArray(@NotNull String[] keys, @NotNull ResourceBundle lang) {
String[] strings = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
strings[i] = lang.getString(keys[i]);
}
return strings;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment