Created
September 4, 2011 16:02
-
-
Save Espenhh/1193067 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ContentMD5VerifikasjonsFilter implements ContainerRequestFilter { | |
@Override | |
public ContainerRequest filter(final ContainerRequest request) { | |
try { | |
// Henter ut alle bytes fra requesten (payload) | |
byte[] entityBytes = IOUtils.toByteArray(request.getEntityInputStream()); // Apache commons | |
// Sjekker bare Content-MD5 dersom det er en request med payload | |
if (entityBytes.length > 0) { | |
String contentMD5Client = request.getHeaderValue("Content-MD5"); | |
// sjekk at Content-MD5-headeren er satt | |
if (contentMD5Client == null) { | |
// Kast feil | |
} | |
// Sjekk at ContentMD5 stemmer | |
validateContentMD5Match(contentMD5Client, entityBytes); | |
} | |
// Gir tilbake en ny InputStream med samme innhold til requesten | |
request.setEntityInputStream(new ByteArrayInputStream(entityBytes)); | |
return request; | |
} catch (IOException e) { | |
// Kast feil | |
} catch (NoSuchAlgorithmException e) { | |
// Kast feil | |
} | |
} | |
private void validateContentMD5Match(final String contentMD5Client, final byte[] entityBytes) throws NoSuchAlgorithmException { | |
// Lager vår egen Content-MD5 (sjekksum) fra requestens payload | |
MessageDigest digest = MessageDigest.getInstance("MD5"); | |
String contentMD5Server = new String(Base64.encodeBase64(digest.digest(entityBytes))); // apache commons | |
// Sjekker at vår sjekksum matcher den i Content-MD5-headeren | |
if (!contentMD5Client.equals(contentMD5Server)) { | |
// Kast feil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment