Java源码示例:net.bither.bitherj.crypto.ECKey
示例1
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
File file = FileUtil.getBackupFile();
String str = Utils.readFile(file);
if (str.contains(address)) {
String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
for (String backupStr : backupStrArray) {
if (backupStr.contains(address)) {
String[] strArray = QRCodeUtil.splitString(backupStr);
if (strArray.length > 3) {
String keyString = backupStr.substring(strArray[0]
.length() + 1);
return PrivateKeyUtil.getECKeyFromSingleString(
keyString, password);
}
}
}
}
return null;
}
示例2
public static List<Address> addPrivateKeyByRandomWithPassphras(IUEntropy iuEntropy, CharSequence password, int count) {
PeerUtil.stopPeer();
List<Address> addressList = new ArrayList<Address>();
for (int i = 0; i < count; i++) {
XRandom xRandom = new XRandom(iuEntropy);
ECKey ecKey = ECKey.generateECKey(xRandom);
ecKey = PrivateKeyUtil.encrypt(ecKey, password);
Address address = new Address(ecKey.toAddress(),
ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
ecKey.clearPrivateKey();
addressList.add(address);
AddressManager.getInstance().addAddress(address);
}
PeerUtil.startPeer();
if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
BackupUtil.backupColdKey(false);
} else {
BackupUtil.backupHotKey();
}
return addressList;
}
示例3
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
File file = FileUtil.getBackupKeyOfHot();
String str = Utils.readFile(file);
if (str.contains(address)) {
String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
for (String backupStr : backupStrArray) {
if (backupStr.contains(address)) {
String[] strArray = QRCodeUtil.splitString(backupStr);
if (strArray.length > 3) {
String keyString = backupStr.substring(strArray[0]
.length() + 1);
return PrivateKeyUtil.getECKeyFromSingleString(
keyString, password);
}
}
}
}
return null;
}
示例4
private static List<ECKey> initPrivateWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getPrivateCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
示例5
private static List<ECKey> initWatchOnlyWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getWatchOnlyCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
示例6
/**
* Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG.
*/
public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) {
checkArgument(threshold > 0);
checkArgument(threshold <= pubkeys.size());
checkArgument(pubkeys.size() <= 16); // That's the max we can represent with a single opcode.
if (pubkeys.size() > 3) {
log.warn("Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3", pubkeys.size());
}
try {
ByteArrayOutputStream bits = new ByteArrayOutputStream();
bits.write(encodeToOpN(threshold));
for (ECKey key : pubkeys) {
writeBytes(bits, key.getPubKey());
}
bits.write(encodeToOpN(pubkeys.size()));
bits.write(OP_CHECKMULTISIG);
return bits.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
示例7
public static boolean checkPubkeysQRCodeContent(String content) {
String[] strs = QRCodeUtil.splitString(content);
for (String str : strs) {
boolean checkCompressed = str.length() == 66 || ((str.length() == 67)
&& (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0));
boolean checkUnCompressed = str.length() == 130 || ((str.length() == 131)
&& (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0));
if(str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0){
str = str.substring(QRCodeUtil.XRANDOM_FLAG.length());
}
org.spongycastle.math.ec.ECPoint ecPoint = ECKey.checkPoint(Utils.hexStringToByteArray(str));
if (ecPoint == null || !ecPoint.isValid()) {
return false;
}
if (!checkCompressed && !checkUnCompressed) {
return false;
}
}
return true;
}
示例8
public static List<Address> formatPublicString(String content) {
String[] strs = QRCodeUtil.splitString(content);
ArrayList<Address> wallets = new ArrayList<Address>();
for (String str : strs) {
boolean isXRandom = false;
if (str.indexOf(QRCodeUtil.XRANDOM_FLAG) == 0) {
isXRandom = true;
str = str.substring(1);
}
byte[] pub = Utils.hexStringToByteArray(str);
org.spongycastle.math.ec.ECPoint ecPoint = ECKey.checkPoint(pub);
if (ecPoint != null && ecPoint.isValid()) {
String addString = Utils.toAddress(Utils.sha256hash160(pub));
Address address = new Address(addString, pub, null, false, isXRandom);
wallets.add(address);
}
}
return wallets;
}
示例9
/**
* will release key
*
* @param key
* @param password
* @return
*/
public static ECKey encrypt(ECKey key, CharSequence password) {
KeyCrypter scrypt = new KeyCrypterScrypt();
KeyParameter derivedKey = scrypt.deriveKey(password);
ECKey encryptedKey = key.encrypt(scrypt, derivedKey);
// Check that the encrypted key can be successfully decrypted.
// This is done as it is a critical failure if the private key cannot be decrypted successfully
// (all bitcoin controlled by that private key is lost forever).
// For a correctly constructed keyCrypter the encryption should always be reversible so it is just being as cautious as possible.
if (!ECKey.encryptionIsReversible(key, encryptedKey, scrypt, derivedKey)) {
// Abort encryption
throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption.");
}
key.clearPrivateKey();
return encryptedKey;
}
示例10
private ECKey getEckey() {
ECKey ecKey = null;
DumpedPrivateKey dumpedPrivateKey = null;
try {
switch (this.importPrivateKeyType) {
case Text:
dumpedPrivateKey = new DumpedPrivateKey(this.content);
ecKey = dumpedPrivateKey.getKey();
break;
case BitherQrcode:
ecKey = PrivateKeyUtil.getECKeyFromSingleString(content, password);
break;
case Bip38:
dumpedPrivateKey = new DumpedPrivateKey(this.content);
ecKey = dumpedPrivateKey.getKey();
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dumpedPrivateKey != null) {
dumpedPrivateKey.clearPrivateKey();
}
}
return ecKey;
}
示例11
public String setSignatureAndGetAddressOfAddressOfSp(byte[] signed, CharSequence password, String firstHotAddress) throws Exception {
String addressOfSP = null;
String message = getBitidString();
byte[] hash = Utils.getPreSignMessage(message);
ECKey key = ECKey.signedMessageToKey(hash, signed);
if (Utils.compareString(address, key.toAddress())) {
throw new SignatureException();
}
String hotAddress = firstHotAddress != null ? firstHotAddress : AddressManager.getInstance().getHdmKeychain().getFirstAddressFromDb();
UploadHDMBidApi uploadHDMBidApi = new UploadHDMBidApi(address, hotAddress, signed, decryptedPassword);
uploadHDMBidApi.handleHttpPost();
boolean result = uploadHDMBidApi.getResult();
if (result) {
encryptedBitherPassword = new EncryptedData(decryptedPassword, password);
ECKey k = new ECKey(decryptedPassword, null);
addressOfSP = k.toAddress();
k.clearPrivateKey();
if (firstHotAddress == null) {
save(addressOfSP);
}
} else {
throw new HttpException("UploadHDMBidApi error");
}
return addressOfSP;
}
示例12
private void initHDAccount(DeterministicKey master, EncryptedData encryptedMnemonicSeed,
EncryptedData encryptedHDSeed, boolean isSyncedComplete) {
String firstAddress;
ECKey k = new ECKey(mnemonicSeed, null);
String address = k.toAddress();
k.clearPrivateKey();
DeterministicKey accountKey = getAccount(master);
DeterministicKey internalKey = getChainRootKey(accountKey, AbstractHD.PathType.INTERNAL_ROOT_PATH);
DeterministicKey externalKey = getChainRootKey(accountKey, AbstractHD.PathType.EXTERNAL_ROOT_PATH);
DeterministicKey key = externalKey.deriveSoftened(0);
firstAddress = key.toAddress();
accountKey.wipe();
master.wipe();
wipeHDSeed();
wipeMnemonicSeed();
hdSeedId = AbstractDb.desktopAddressProvider.addHDKey(encryptedMnemonicSeed.toEncryptedString(),
encryptedHDSeed.toEncryptedString(), firstAddress, isFromXRandom, address, externalKey.getPubKeyExtended(), internalKey
.getPubKeyExtended());
internalKey.wipe();
externalKey.wipe();
}
示例13
public ArrayList<byte[]> signWithCold(List<byte[]> unsignedHashes,
CharSequence password,
List<PathTypeIndex> pathTypeIndexList) {
ArrayList<byte[]> sigs = new ArrayList<byte[]>();
for (int i = 0;
i < unsignedHashes.size();
i++) {
PathTypeIndex pathTypeIndex = pathTypeIndexList.get(i);
DeterministicKey key;
if (pathTypeIndex.pathType == PathType.EXTERNAL_ROOT_PATH) {
key = getExternalKey(pathTypeIndex.index, password);
System.out.println("pub:" + Base58.encode(key.getPubKey()));
} else {
key = getInternalKey(pathTypeIndex.index, password);
}
ECKey.ECDSASignature signed = key.sign(unsignedHashes.get(i));
sigs.add(signed.encodeToDER());
key.wipe();
}
return sigs;
}
示例14
public List<byte[]> signHashes(List<byte[]> unsignedInHashes, CharSequence passphrase) throws
PasswordException {
ECKey key = PrivateKeyUtil.getECKeyFromSingleString(this.getFullEncryptPrivKey(), passphrase);
if (key == null) {
throw new PasswordException("do not decrypt eckey");
}
KeyParameter assKey = key.getKeyCrypter().deriveKey(passphrase);
List<byte[]> result = new ArrayList<byte[]>();
for (byte[] unsignedInHash : unsignedInHashes) {
TransactionSignature signature = new TransactionSignature(key.sign(unsignedInHash,
assKey), TransactionSignature.SigHash.ALL, false);
result.add(ScriptBuilder.createInputScript(signature, key).getProgram());
}
key.clearPrivateKey();
return result;
}
示例15
/**
* Adds a new and fully signed input for the given parameters. Note that this method is
* <b>not</b> thread safe
* and requires external synchronization. Please refer to general documentation on Bitcoin
* scripting and contracts
* to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form
* of this method
* that sets them to typical defaults.
*
* @throws net.bither.bitherj.exception.ScriptException if the scriptPubKey is not a pay to address or pay to pubkey script.
*/
public In addSignedInput(Out prevOut, Script scriptPubKey, ECKey sigKey,
TransactionSignature.SigHash sigHash, boolean anyoneCanPay) throws
ScriptException {
In input = new In(this, new byte[]{}, prevOut);
addInput(input);
byte[] hash = hashForSignature(ins.size() - 1, scriptPubKey, sigHash, anyoneCanPay);
ECKey.ECDSASignature ecSig = sigKey.sign(hash);
TransactionSignature txSig = new TransactionSignature(ecSig, sigHash, anyoneCanPay);
if (scriptPubKey.isSentToRawPubKey()) {
input.setInSignature(ScriptBuilder.createInputScript(txSig).getProgram());
} else if (scriptPubKey.isSentToAddress()) {
input.setInSignature(ScriptBuilder.createInputScript(txSig, sigKey).getProgram());
} else {
throw new ScriptException("Don't know how to sign for this kind of scriptPubKey: " +
scriptPubKey);
}
return input;
}
示例16
private byte[] getSignPubs(byte[] messageHash,
ECKey.ECDSASignature sig, List<byte[]> pubs) {
for (int i = 0; i < 4; i++) {
ECPoint point = ECKey.recoverECPointFromSignature(i, sig, messageHash);
ECKey ecKeyCompress = new ECKey(null, point.getEncoded(true));
ECKey ecKeyUnCompress = new ECKey(null, point.getEncoded(false));
for (int j = 0; j < pubs.size(); j++) {
if (Arrays.equals(ecKeyCompress.getPubKey(), pubs.get(j))) {
return ecKeyCompress.getPubKey();
}
if (Arrays.equals(ecKeyUnCompress.getPubKey(), pubs.get(j))) {
return ecKeyUnCompress.getPubKey();
}
}
}
return null;
}
示例17
private static ECKey getEckeyFormBackupHot(String address, CharSequence password) {
File file = FileUtil.getBackupFile();
String str = Utils.readFile(file);
if (str.contains(address)) {
String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
for (String backupStr : backupStrArray) {
if (backupStr.contains(address)) {
String[] strArray = QRCodeUtil.splitString(backupStr);
if (strArray.length > 3) {
String keyString = backupStr.substring(strArray[0]
.length() + 1);
return PrivateKeyUtil.getECKeyFromSingleString(
keyString, password);
}
}
}
}
return null;
}
示例18
public static List<Address> addPrivateKeyByRandomWithPassphras(IUEntropy iuEntropy, CharSequence password, int count) {
PeerUtil.stopPeer();
List<Address> addressList = new ArrayList<Address>();
for (int i = 0; i < count; i++) {
XRandom xRandom = new XRandom(iuEntropy);
ECKey ecKey = ECKey.generateECKey(xRandom);
ecKey = PrivateKeyUtil.encrypt(ecKey, password);
Address address = new Address(ecKey.toAddress(),
ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), ecKey.isFromXRandom());
ecKey.clearPrivateKey();
addressList.add(address);
AddressManager.getInstance().addAddress(address);
}
PeerUtil.startPeer();
if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
BackupUtil.backupColdKey(false);
} else {
BackupUtil.backupHotKey();
}
return addressList;
}
示例19
public static ECKey getEckeyFromBackup(String address, CharSequence password) {
if (UserPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
return getEckeyFormBackupCold(address, password);
} else {
return getEckeyFormBackupHot(address, password);
}
}
示例20
private static ECKey getEckeyFormBackupCold(String address, CharSequence password) {
try {
File[] files = FileUtil.getBackupDir().listFiles();
if (files == null) {
return null;
}
files = FileUtil.orderByDateDesc(files);
for (int i = files.length - 1;
i >= 0;
i++) {
File file = files[i];
String str = Utils.readFile(file);
if (str.contains(address)) {
String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
for (String backupStr : backupStrArray) {
if (backupStr.contains(address)) {
String[] strArray = QRCodeUtil.splitString(backupStr);
if (strArray.length > 3) {
String keyString = backupStr
.substring(strArray[0].length() + 1);
return PrivateKeyUtil.getECKeyFromSingleString(
keyString, password);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例21
public static Check initCheckForPrivateKey(
final Address address, final SecureCharSequence password) {
String title = String.format(LocaliserUtils.getString("check_address_private_key_title"), address
.getShortAddress());
Check check = new Check(title, new ICheckAction() {
@Override
public boolean check() {
boolean result = new PasswordSeed(address.getAddress(), address.getFullEncryptPrivKey()).checkPassword(password);
if (!result) {
try {
ECKey eckeyFromBackup = BackupUtil.getEckeyFromBackup(
address.getAddress(), password);
if (eckeyFromBackup != null) {
String encryptPrivateKey = PrivateKeyUtil.getEncryptedString(eckeyFromBackup);
if (!Utils.isEmpty(encryptPrivateKey)) {
address.recoverFromBackup(encryptPrivateKey);
result = true;
}
eckeyFromBackup.clearPrivateKey();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
password.wipe();
}
}
return result;
}
});
return check;
}
示例22
public boolean setQrCodeResult(String qr) {
if (!Utils.isEmpty(qr)) {
try {
String[] stringArray = QRCodeUtil.splitString(qr);
sigs = new ArrayList<TransactionSignature>();
for (String str : stringArray) {
if (!Utils.isEmpty(str)) {
TransactionSignature transactionSignature = new
TransactionSignature(ECKey.ECDSASignature.decodeFromDER
(Utils.hexStringToByteArray(str)),
TransactionSignature.SigHash.ALL, false);
sigs.add(transactionSignature);
}
}
} catch (Exception e) {
sigs = null;
e.printStackTrace();
new MessageDialog(LocaliserUtils.getString("send_failed")).showMsg();
}
} else {
sigs = null;
}
try {
lock.lock();
fetchedCondition.signal();
} finally {
lock.unlock();
}
return true;
}
示例23
public void importPrivateKey() {
if (importPrivateKeyType != ImportPrivateKeyType.Text) {
Address address = initPrivateKey();
importPrivateKey(address);
return;
}
boolean isCompressed = getIsCompressed();
final ECKey compressKey = initEcKey(true);
if (compressKey == null) {
return;
}
final ECKey uncompressedKey = initEcKey(false);
if (uncompressedKey == null) {
return;
}
DialogImportPrivateKeyAddressValidation dialogImportPrivateKeyAddressValidation = new DialogImportPrivateKeyAddressValidation(activity, compressKey.toAddress(), uncompressedKey.toAddress(), isCompressed, new Runnable() {
@Override
public void run() {
Address compressAddress = initPrivateKey(true);
if (compressAddress != null) {
importPrivateKey(compressAddress);
}
}
}, new Runnable() {
@Override
public void run() {
Address uncompressedAddress = initPrivateKey(false);
if (uncompressedAddress != null) {
importPrivateKey(uncompressedAddress);
}
}
});
dialogImportPrivateKeyAddressValidation.show();
}
示例24
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RequestCode) {
if (resultCode == RESULT_OK) {
final String qr = data.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT);
try {
String[] stringArray = QRCodeUtil.splitString(qr);
sigs = new ArrayList<TransactionSignature>();
for (String str : stringArray) {
if (!Utils.isEmpty(str)) {
TransactionSignature transactionSignature = new
TransactionSignature(ECKey.ECDSASignature.decodeFromDER
(Utils.hexStringToByteArray(str)),
TransactionSignature.SigHash.ALL, false);
sigs.add(transactionSignature);
}
}
} catch (Exception e) {
sigs = null;
e.printStackTrace();
DropdownMessage.showDropdownMessage(HdmSendActivity.this,
R.string.send_failed);
}
} else {
sigs = null;
}
try {
lock.lock();
fetchedCondition.signal();
} finally {
lock.unlock();
}
return true;
}
return false;
}
示例25
public static ECKey getEckeyFromBackup(String address, CharSequence password) {
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
return getEckeyFormBackupCold(address, password);
} else {
return getEckeyFormBackupHot(address, password);
}
}
示例26
private static ECKey getEckeyFormBackupCold(String address, CharSequence password) {
if (!FileUtil.existSdCardMounted()) {
return null;
}
try {
File[] files = FileUtil.getBackupSdCardDir().listFiles();
if (files == null) {
return null;
}
files = FileUtil.orderByDateDesc(files);
for (int i = files.length - 1;
i >= 0;
i++) {
File file = files[i];
String str = Utils.readFile(file);
if (str.contains(address)) {
String[] backupStrArray = str.split(PrivateKeyUtil.BACKUP_KEY_SPLIT_MUTILKEY_STRING);
for (String backupStr : backupStrArray) {
if (backupStr.contains(address)) {
String[] strArray = QRCodeUtil.splitString(backupStr);
if (strArray.length > 3) {
String keyString = backupStr
.substring(strArray[0].length() + 1);
return PrivateKeyUtil.getECKeyFromSingleString(
keyString, password);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例27
public static List<Address> addPrivateKeyByRandomWithPassphras(BlockchainService service, IUEntropy iuEntropy, CharSequence password, int count) {
if (service != null) {
service.stopAndUnregister();
}
List<Address> addressList = new ArrayList<Address>();
for (int i = 0; i < count; i++) {
XRandom xRandom = new XRandom(iuEntropy);
ECKey ecKey = ECKey.generateECKey(xRandom);
ecKey = PrivateKeyUtil.encrypt(ecKey, password);
Address address = new Address(ecKey.toAddress(),
ecKey.getPubKey(), PrivateKeyUtil.getEncryptedString(ecKey), true, ecKey.isFromXRandom());
ecKey.clearPrivateKey();
addressList.add(address);
AddressManager.getInstance().addAddress(address);
}
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
BackupUtil.backupColdKey(false);
} else {
BackupUtil.backupHotKey();
}
if (service != null) {
service.startAndRegister();
}
return addressList;
}
示例28
public static Check initCheckForPrivateKey(
final Address address, final SecureCharSequence password) {
String title = String.format(BitherApplication.mContext.getString(R.string
.check_address_private_key_title), address.getShortAddress());
Check check = new Check(title, new ICheckAction() {
@Override
public boolean check() {
PasswordSeed passwordSeed = new PasswordSeed(address.getAddress(), address.getFullEncryptPrivKey());
boolean result = passwordSeed.checkPassword(password);
if (!result) {
try {
ECKey eckeyFromBackup = BackupUtil.getEckeyFromBackup(
address.getAddress(), password);
if (eckeyFromBackup != null) {
String encryptPrivateKey = PrivateKeyUtil.getEncryptedString(eckeyFromBackup);
eckeyFromBackup.clearPrivateKey();
if (!Utils.isEmpty(encryptPrivateKey)) {
address.recoverFromBackup(encryptPrivateKey);
result = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
password.wipe();
return result;
}
});
return check;
}
示例29
private boolean checkValue(byte[] data) {
BigInteger value = new BigInteger(1, data);
if (value.compareTo(BigInteger.ZERO) == 0 || value.compareTo(ECKey.CURVE.getN()) == 0) {
return false;
}
return true;
}
示例30
private boolean checkValue(byte[] data) {
BigInteger value = new BigInteger(1, data).mod(ECKey.CURVE.getN());
if (value.compareTo(BigInteger.ZERO) == 0) {
return false;
}
return true;
}