Skip to content

Commit

Permalink
fix: remove leading zero bytes of dh secret
Browse files Browse the repository at this point in the history
  • Loading branch information
XuXiangJun committed Sep 25, 2024
1 parent a4ecc8c commit f72e88c
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions lib-blufi/src/main/java/blufi/espressif/security/BlufiDH.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package blufi.espressif.security;

import android.util.Log;

import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
Expand All @@ -18,6 +20,8 @@
import javax.crypto.spec.DHPublicKeySpec;

public class BlufiDH {
private static final String TAG = "BlufiDH";

private final BigInteger mP;
private final BigInteger mG;

Expand Down Expand Up @@ -67,9 +71,25 @@ public void generateSecretKey(BigInteger y) {
ka.doPhase(publicKey, true);

// Generate the secret key
mSecretKey = ka.generateSecret();
byte[] tempSecret = ka.generateSecret();
int offset = 0;
for (byte b : tempSecret) {
if (b == 0) {
offset++;
} else {
break;
}
}
byte[] secretKey;
if (offset == 0) {
secretKey = tempSecret;
} else {
secretKey = new byte[tempSecret.length - offset];
System.arraycopy(tempSecret, offset, secretKey, 0, tempSecret.length - offset);
}
mSecretKey = secretKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException e) {
e.printStackTrace();
Log.w(TAG, e);
}
}

Expand All @@ -90,7 +110,7 @@ private static Key[] generateKeys(BigInteger p, BigInteger g, int length) {
} catch (NoSuchAlgorithmException
| InvalidAlgorithmParameterException
| ClassCastException e) {
e.printStackTrace();
Log.w(TAG, e);

return null;
}
Expand Down

0 comments on commit f72e88c

Please sign in to comment.