use of com.macasaet.fernet.Key in project fernet-java8 by l0s.
the class AuthenticationResource method createSession.
/**
* This is an example of an endpoint that generates a new Fernet token. The
* client authenticates using this method then can use the token provided to
* perform secured operations. The client may, at their discretion, store
* the token insecurely (e.g. in a cookie or browser storage) since it will
* no longer be valid after the TTL (60 seconds by default).
*
* @param request
* client credentials to create a new session token
* @return a Fernet token
*/
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String createSession(final LoginRequest request) {
final User user = repository.findUser(request.getUsername());
if (user != null && user.isPasswordCorrect(request.getSingleRoundPasswordHash())) {
// password is correct, so generate an ephemeral session
// store the session ID in the token payload
final Session session = new Session(request.getUsername());
sessionRepository.saveSession(session);
final Key key = keySupplier.get().iterator().next();
final Token token = Token.generate(random, key, session.getId().toString());
return token.serialise();
}
throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).entity("invalid login").build());
}
use of com.macasaet.fernet.Key in project fernet-java8 by l0s.
the class TokenInjectionIT method verifyFailedForgery.
/**
* This demonstrates a client who attempts to forge a Fernet token but
* cannot do so without knowing the secret key.
*/
@Test
public final void verifyFailedForgery() {
// given
final SecureRandom random = new SecureRandom();
final Key invalidKey = Key.generateKey(random);
final Token forgedToken = Token.generate(random, invalidKey, UUID.randomUUID().toString());
final String tokenString = forgedToken.serialise();
// when / then
assertThrows(ForbiddenException.class, () -> target("secrets").request().header("Authorization", "Bearer\t" + tokenString).get(String.class));
}
use of com.macasaet.fernet.Key in project fernet-java8 by l0s.
the class CreateSimpleKey method main.
public static final void main(final String... args) throws Exception {
final SecureRandom random = new SecureRandom();
final Key key = Key.generateKey(random);
try (FileOutputStream outputStream = new FileOutputStream("simple-key")) {
key.writeTo(outputStream);
}
/*
aws secretsmanager create-secret --name simple-fernet-key --secret-binary fileb://simple-key
{
"ARN": "arn:aws:secretsmanager:<region>:<account_id>:secret:simple-fernet-key-<random_value>",
"Name": "simple-fernet-key",
"VersionId": "<uuidv4>"
}
*/
}
use of com.macasaet.fernet.Key in project fernet-java8 by l0s.
the class SecretsManagerTest method verifyPutSecretValueStoresKey.
@Test
public final void verifyPutSecretValueStoresKey() throws IOException {
// given
final String expected = "expected";
final Key key = mock(Key.class);
final Answer<?> answer = new Answer<Void>() {
public Void answer(final InvocationOnMock invocation) throws Throwable {
final OutputStream stream = invocation.getArgument(0);
stream.write(expected.getBytes("UTF-8"));
return null;
}
};
doAnswer(answer).when(key).writeTo(any(OutputStream.class));
// when
manager.putSecretValue("secret", "version", key, PREVIOUS);
// then
final PutSecretValueRequest request = new PutSecretValueRequest();
request.setSecretId("secret");
request.setClientRequestToken("version");
request.setVersionStages(singleton("AWSPREVIOUS"));
request.setSecretBinary(ByteBuffer.wrap(expected.getBytes("UTF-8")));
verify(delegate).putSecretValue(eq(request));
}
use of com.macasaet.fernet.Key in project fernet-java8 by l0s.
the class MultiFernetKeyRotator method createSecret.
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
protected void createSecret(final String secretId, final String clientRequestToken) {
final ByteBuffer currentSecret = getSecretsManager().getSecretStage(secretId, CURRENT);
try {
if (currentSecret.remaining() % fernetKeySize != 0) {
throw new IllegalStateException("There must be a multiple of 32 bytes.");
}
final int numKeys = currentSecret.remaining() / fernetKeySize;
List<Key> keys = new ArrayList<>(numKeys + 1);
while (currentSecret.hasRemaining()) {
final byte[] signingKey = new byte[16];
currentSecret.get(signingKey);
final byte[] encryptionKey = new byte[16];
currentSecret.get(encryptionKey);
final Key key = new Key(signingKey, encryptionKey);
keys.add(key);
wipe(signingKey);
wipe(encryptionKey);
}
final Key keyToStage = Key.generateKey(getRandom());
keys.add(0, keyToStage);
// max active keys + one pending
final int desiredSize = getMaxActiveKeys() + 1;
if (keys.size() > desiredSize) {
keys = keys.subList(0, desiredSize);
}
getSecretsManager().putSecretValue(secretId, clientRequestToken, keys, PENDING);
} finally {
wipe(currentSecret);
}
getLogger().info("createSecret: Successfully put secret for ARN {} and version {}.", secretId, clientRequestToken);
}
Aggregations