Be less finnicky about session key formats

This commit is contained in:
Paul Schaub 2022-11-06 20:23:01 +01:00
parent dd5d790e21
commit aa953428ee
3 changed files with 20 additions and 13 deletions

View File

@ -175,24 +175,22 @@ public class DecryptCmd extends AbstractSopCmd {
}
private void setWithSessionKeys(List<String> withSessionKey, Decrypt decrypt) {
Pattern sessionKeyPattern = Pattern.compile("^\\d+:[0-9A-F]+$");
for (String sessionKeyFile : withSessionKey) {
String sessionKey;
String sessionKeyString;
try {
sessionKey = stringFromInputStream(getInput(sessionKeyFile));
sessionKeyString = stringFromInputStream(getInput(sessionKeyFile));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!sessionKeyPattern.matcher(sessionKey).matches()) {
String errorMsg = getMsg("sop.error.input.malformed_session_key");
throw new IllegalArgumentException(errorMsg);
}
String[] split = sessionKey.split(":");
byte algorithm = (byte) Integer.parseInt(split[0]);
byte[] key = HexUtil.hexToBytes(split[1]);
SessionKey sessionKey;
try {
decrypt.withSessionKey(new SessionKey(algorithm, key));
sessionKey = SessionKey.fromString(sessionKeyString);
} catch (IllegalArgumentException e) {
String errorMsg = getMsg("sop.error.input.malformed_session_key");
throw new IllegalArgumentException(errorMsg, e);
}
try {
decrypt.withSessionKey(sessionKey);
} catch (SOPGPException.UnsupportedOption unsupportedOption) {
String errorMsg = getMsg("sop.error.feature_support.option_not_supported", OPT_WITH_SESSION_KEY);
throw new SOPGPException.UnsupportedOption(errorMsg, unsupportedOption);

View File

@ -12,7 +12,7 @@ import sop.util.HexUtil;
public class SessionKey {
private static final Pattern PATTERN = Pattern.compile("^(\\d):([0-9a-fA-F]+)$");
private static final Pattern PATTERN = Pattern.compile("^(\\d):([0-9A-F]+)$");
private final byte algorithm;
private final byte[] sessionKey;
@ -62,6 +62,7 @@ public class SessionKey {
}
public static SessionKey fromString(String string) {
string = string.trim().toUpperCase().replace("\n", "");
Matcher matcher = PATTERN.matcher(string);
if (!matcher.matches()) {
throw new IllegalArgumentException("Provided session key does not match expected format.");

View File

@ -20,6 +20,14 @@ public class SessionKeyTest {
assertEquals(string, sessionKey.toString());
}
@Test
public void fromLowerStringTest() {
String string = "9:FCA4BEAF687F48059CACC14FB019125CD57392BAB7037C707835925CBF9F7BCD";
String lowercaseWithTrailingNewLine = "9:fca4beaf687f48059cacc14fb019125cd57392bab7037c707835925cbf9f7bcd\n";
SessionKey sessionKey = SessionKey.fromString(lowercaseWithTrailingNewLine);
assertEquals(string, sessionKey.toString());
}
@Test
public void toStringTest() {
SessionKey sessionKey = new SessionKey((byte) 9, HexUtil.hexToBytes("FCA4BEAF687F48059CACC14FB019125CD57392BAB7037C707835925CBF9F7BCD"));