Skip to content

Commit

Permalink
Fix size of encrypted bytes when encrypting private keys. Also change…
Browse files Browse the repository at this point in the history
… decrypting to use similar code.
  • Loading branch information
schildbach authored and mikehearn committed Apr 22, 2014
1 parent 53147fa commit b4644fd
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions core/src/main/java/com/google/bitcoin/crypto/KeyCrypterScrypt.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.Arrays;

import static com.google.common.base.Preconditions.checkNotNull;

Expand Down Expand Up @@ -173,11 +174,10 @@ public EncryptedPrivateKey encrypt(byte[] plainBytes, KeyParameter aesKey) throw
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
cipher.init(true, keyWithIv);
byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
int length = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
final int length2 = cipher.doFinal(encryptedBytes, length1);

cipher.doFinal(encryptedBytes, length);

return new EncryptedPrivateKey(iv, encryptedBytes);
return new EncryptedPrivateKey(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
} catch (Exception e) {
throw new KeyCrypterException("Could not encrypt bytes.", e);
}
Expand All @@ -204,16 +204,11 @@ public byte[] decrypt(EncryptedPrivateKey privateKeyToDecode, KeyParameter aesKe
cipher.init(false, keyWithIv);

byte[] cipherBytes = privateKeyToDecode.getEncryptedBytes();
int minimumSize = cipher.getOutputSize(cipherBytes.length);
byte[] outputBuffer = new byte[minimumSize];
int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, outputBuffer, 0);
int length2 = cipher.doFinal(outputBuffer, length1);
int actualLength = length1 + length2;

byte[] decryptedBytes = new byte[actualLength];
System.arraycopy(outputBuffer, 0, decryptedBytes, 0, actualLength);
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
final int length2 = cipher.doFinal(decryptedBytes, length1);

return decryptedBytes;
return Arrays.copyOf(decryptedBytes, length1 + length2);
} catch (Exception e) {
throw new KeyCrypterException("Could not decrypt bytes", e);
}
Expand Down

0 comments on commit b4644fd

Please sign in to comment.