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

Random (missing) Output on decrypt #88

Closed lordrex34 closed 3 years ago

lordrex34 commented 3 years ago

Hello,

Code to reproduce: https://gist.github.com/lordrex34/24d156791658127470c9f20fe8c13922

I made this little gist to help reproduce the problem.

Dependency:

implementation "com.goterl.lazycode:lazysodium-java:4.3.0"
implementation "net.java.dev.jna:jna:5.6.0"

I do 3 to 5 trial runs of this and I get random outcomes.

Output 1:

ENCRYPTED: [17, 21, -31, -77, -16, -81, 66, 6, -89, 107, 111, 68, 27, 102, -80, 89, -91, -117, -43, 62, -54, 40, 49, 58, -48, -104, -13, -122, 61, 59, -82]
DECRYPTED: [77, 121, 32, 116, 101, 115, 116, 32, 109, 101, 115, 115, 97, 103, 101]
Decoded: My test message

Output 2:

ENCRYPTED: [-84, -59, 87, -85, -65, -52, 89, 42, 11, -14, -44, 18, -11, -1, -33, -5, 28, -66, 22, 11, 111, -59, -31, 45, 106, 64, -128, 38, 35, 2, -11]
DECRYPTED: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Decoded:                

Output 1 ought to be the normal output, but I get it only few times and output 2 occurs mostly.

I have tried varying LibraryLoader.Mode several times without luck. I even tried using as path libsodium.dll that I built.

Do you have any idea what am I supposed to do?

gurpreet- commented 3 years ago

Hi @lordrex34,

Yes this is usually a charset issue or a parameter being incorrect somewhere issue.

I think the issue is in the hardcoding of the nonce value to value. Instead of:

public Test() {
    this.key = LAZY_SODIUM_JAVA.cryptoSecretBoxKeygen().getAsBytes();
    this.nonce = LAZY_SODIUM_JAVA.nonce(10);
}

it should be:

public Test() {
    this.key = LAZY_SODIUM_JAVA.cryptoSecretBoxKeygen().getAsBytes();
    this.nonce = LAZY_SODIUM_JAVA.nonce(SecretBox.NONCEBYTES);
}
lordrex34 commented 3 years ago

Thanks