我正在尝试用c ++重写此代码,从而创建一个比特币迷你私钥
using System;
using System.Text;
using Org.BouncyCastle.Security;
public string CreateRandomMinikey(){
string keytotry = "S6c56bnXQiBjk9mqSYE7ykVQ7NzrQA";
char[] chars = keytotry.ToCharArray();
char[] charstest = (keytotry + "?").ToCharArray();
while (Util.ComputeSha256(utf8.GetBytes(charstest))[0] != 0) {// hash sha256 the key & check if the first character was '0'
// As long as key doesn't pass typo check, increment it.
for (int i = chars.Length - 1; i >= 0; i--) {
char c = chars[i];
if (c == '9') {
charstest[i] = chars[i] = 'A';
break;
} else if (c == 'H') {
charstest[i] = chars[i] = 'J';
break;
} else if (c == 'N') {
charstest[i] = chars[i] = 'P';
break;
} else if (c == 'Z') {
charstest[i] = chars[i] = 'a';
break;
} else if (c == 'k') {
charstest[i] = chars[i] = 'm';
break;
} else if (c == 'z') {
charstest[i] = chars[i] = '2';
// No break - let loop increment prior character.
} else {
charstest[i] = chars[i] = ++c;
break;
}
}
}
string result = new string(chars);//expect S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy
return result;
}
当我转换为c ++时,这里是我的代码
#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <cstring>
#include "sha256.h"
using namespace std;
int main()
{
string input = "S6c56bnXQiBjk9mqSYE7ykVQ7NzrQA";
string inputcharstest = input+"?";
char * chars = new char[input.size() + 1];
strcpy(chars, input.c_str());//convert input to char array
char * charstest = new char[inputcharstest.size() + 1];
strcpy(charstest, inputcharstest.c_str());// convert inputcharstest to char array
string output = sha256(inputcharstest); //hash sha256 inputcharstest to check typo
while (output[0] != '0') {
for (int i = strlen(chars) - 1; i >= 0; i--) {
char c = chars[i];
if (c == '9') {
charstest[i] = chars[i] = 'A';
break;
}
else if (c == 'H') {
charstest[i] = chars[i] = 'J';
break;
}
else if (c == 'N') {
charstest[i] = chars[i] = 'P';
break;
}
else if (c == 'Z') {
charstest[i] = chars[i] = 'a';
break;
}
else if (c == 'k') {
charstest[i] = chars[i] = 'm';
break;
}
else if (c == 'z') {
charstest[i] = chars[i] = '2';
}
else {
charstest[i] = chars[i] = ++c;
break;
}
}
}
string result = string(chars); //expect S6c56bnXQiBjk9mqSYE7ykVQ7NzrRy
cout << "input('" << input << "'):" << result << endl;
return 0;
}
代码被卡住,并且在控制台应用程序上运行时返回空白,我调试并发现它永远卡在while循环中。我可以问一下这个问题吗?该如何解决?
答案 0 :(得分:1)
这里您每次都在更改字符串的内容:
char[] charstest = (keytotry + "?").ToCharArray();
while (Util.ComputeSha256(utf8.GetBytes(charstest))[0] != 0) {
charstest
在每次循环运行中都会发生变化,因此while
中的测试可以在某个时刻终止。但是,在C ++代码中,您没有这样做:
string output = sha256(inputcharstest); //hash sha256 inputcharstest to check typo
while (output[0] != '0') {
在这里,您只在循环之前执行一次哈希,然后在循环中不再执行哈希。循环根本不会改变output
,break
也不会while
,因此如果output[0] != '0'
是第一次true
,它将永远是真的,因此是无限循环。