| 
 Duplicate :   
 | 
The DIFFIE HELLMAN implementation uses the BigInteger class.
The Conversion of BigInteger to the byte array sometimes adds the 0 byte for 
the sign. And if the sign byte is removed by the  KeyAgreement.generateSecret()
method, the KeyAgreement.generateSecret(byte[],int) does not removes it.
To reproduce the bug, the attached com.oracle.df_test.Test can be used.
The com/sun/crypto/provider/DHKeyAgreement.java uses the following algorithms
to detect the sign byte.
   protected byte[]  [More ...] engineGenerateSecret()
...
        if ((tmpResult.bitLength() % 8) == 0) {
It looks correct
But engineGenerateSecret(byte[] sharedSecret, int offset)
uses other approach
        if ((secret.length << 3) != modulus.bitLength()) {
This approach has two issues
1. It always remove leading byte if the modulus.bitLength() is dividable by 8
2. It does not remove the sign byte in some other cases.