Decrypt my private key using KeyCrypter

1

I am trying to decrypt my private key bytes using the KeyCrypter interface. But i do not know how to implement and call the decrypt() function. Initially i encrypt the bytes of my Private Key of my ECKey.

Here is my code:

private ECKey myKey;
private CharSequence password = "myPassword";


public KeyParameter deriveKey(CharSequence password)
            throws KeyCrypterException {

        String s = password.toString();
        KeyParameter keyParameter = new KeyParameter(s.getBytes());

        return keyParameter;
    }

    public EncryptedData encrypt(byte[] plainBytes,
            org.spongycastle.crypto.params.KeyParameter aesKey)
            throws KeyCrypterException {

        plainBytes = myKey.getPrivKeyBytes();

        EncryptedData myData = new EncryptedData(plainBytes, aesKey.getKey());
        System.out.println(myData);

        return myData;
    }

    public byte[] decrypt(EncryptedData encryptedBytesToDecode,
            KeyParameter aesKey) throws KeyCrypterException {
        // TODO Auto-generated method stub

        return null;
    }

which is the byte [] result=...returning from my decrypt() function?

gtopal

Posted 2016-01-11T13:12:50.040

Reputation: 341

Answers

2

Attempting to implement the interface KeyCrypter is a worthy exercise but it seems to require more than a few simple lines of code. bitcoinj offers one implementation with the class KeyCrypterScrypt and you may wish to look at the source file for this class. However, because this implementation exists, you do not need to provide your own implementation of KeyCrypter if all you want to do is have the ability to encrypt and decrypt keys. This can be done as follows:

import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.spongycastle.crypto.params.KeyParameter;

public class Test {

  public static void main(String[] args){

  ECKey k1 = new ECKey(); // some random key

  // encrypting a key
  KeyCrypter crypter1 = new KeyCrypterScrypt();
  KeyParameter aesKey1 = crypter1.deriveKey("some arbitrary passphrase");
  ECKey k2 = k1.encrypt(crypter1, aesKey1);
  System.out.println(k2.isEncrypted()); // true

  // decrypting a key
  KeyCrypter crypter2 = k2.getKeyCrypter();
  KeyParameter aesKey2 = crypter2.deriveKey("some arbitrary passphrase");
  ECKey k3 = k2.decrypt(aesKey2);
  System.out.println(k1.equals(k3));  // true
  }
}

Sven Williamson

Posted 2016-01-11T13:12:50.040

Reputation: 1 314