terl / lazysodium-java

A Java implementation of the Libsodium crypto library. For the lazy dev.
https://github.com/terl/lazysodium-java/wiki
Mozilla Public License 2.0
134 stars 46 forks source link

cryptoSign(String message, Key secretKey) does not use messageEncoder #131

Open gmulders opened 10 months ago

gmulders commented 10 months ago

The second method is converting the key directly to a hex string instead of delegating this to the messageEncoder. In the called method (the first) then the key is decoded with the messageEncoder to its bytes. This will cause the signing to fail if the messageEncoder is a base64 encoder.

@Override
public String cryptoSign(String message, String secretKey) throws SodiumException {
    byte[] messageBytes = bytes(message);
    byte[] secretKeyBytes = messageEncoder.decode(secretKey);
    byte[] signedMessage = randomBytesBuf(Sign.BYTES + messageBytes.length);
    boolean res = cryptoSign(signedMessage, messageBytes, messageBytes.length, secretKeyBytes);

    if (!res) {
        throw new SodiumException("Could not sign your message.");
    }

    return messageEncoder.encode(signedMessage);
}

@Override
public String cryptoSign(String message, Key secretKey) throws SodiumException {
    return cryptoSign(message, secretKey.getAsHexString());
}

Possible solution

A better way would be to use the bytes from the Key:

@Override
public String cryptoSign(String message, Key secretKey) throws SodiumException {
    byte[] messageBytes = bytes(message);
    byte[] secretKeyBytes = secretKey.getAsBytes();
    byte[] signedMessage = randomBytesBuf(Sign.BYTES + messageBytes.length);
    boolean res = cryptoSign(signedMessage, messageBytes, messageBytes.length, secretKeyBytes);

    if (!res) {
        throw new SodiumException("Could not sign your message.");
    }

    return messageEncoder.encode(signedMessage);
}

@Override
public String cryptoSign(String message, String secretKey) throws SodiumException {
    return cryptoSign(message, Key.fromBytes(messageEncoder.encode(secretKey)));
}