TRON iOS Objective-C address generate
Related Document: TRON公链概览
引用文件来源于这里: PocketEOS-IOS
Secrect Key Generation:
#import <Security/Security.h>
#import "NSObject+Extension.h"
#import "sha3.h"
#include "libbase58.h"
#include "sha2.h"
#include "uECC.h"
...
int length = 32;
uint8_t randomBytes[length];
int randomResult = SecRandomCopyBytes(kSecRandomDefault, length, randomBytes);
if(randomResult == 0) {
NSMutableString *randomSecrect =
[[NSMutableString alloc] initWithCapacity:length * 2];
for(NSInteger index = 0; index < length; index++){
[randomSecrect appendFormat:@"%02x", randomBytes[index]];
}
}
Public Key & Address Generation:
//这是测试用的私钥字符串对象
NSString *hexString = @"53a33b690d1867a01c464b8129d0fbedb04adaf22628cbe30b302155f4374321";
//转换成char数组
unsigned char *myBuffer = (unsigned char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
unsigned int anInt;
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
myBuffer[i / 2] = (unsigned char)anInt;
}
printf("private key:\n");
[NSObject out_Hex:myBuffer andLength:32];
//生成公钥
uECC_compute_public_key(myBuffer,pub);
printf("public key:\n");
[NSObject out_Hex:pub andLength:64];
//SHA3 KECCAK-256
unsigned char testResult[64];
struct SHA3_CTX ctx;
sha3_256_Init(&ctx);
sha3_Update(&ctx, pub, sizeof(pub));
//注意keccak_Final与sha3_Final在reset时参数不同
keccak_Final(&ctx, testResult);
printf("SHA3:\n");
[NSObject out_Hex:testResult andLength:32];
//取其最后20字节。在前面填充41
uint8_t originAddress[21];
memcpy(originAddress +1, testResult+(32-20), 20);
originAddress[0]=0x41;
printf("Address:\n");
[NSObject out_Hex:originAddress andLength:21];
//做两次sha256计算
uint8_t sha1[32];
sha256_Raw(originAddress, 21, sha1);
printf("SHA256_0:\n");
[NSObject out_Hex:sha1 andLength:32];
uint8_t sha2[32];
sha256_Raw(sha1, 32, sha2);
printf("SHA256_1:\n");
[NSObject out_Hex:sha2 andLength:32];
//取其前4字节得到校验码
uint8_t checksum[4];
memcpy(checksum, sha2, 4);
printf("checkSum:\n");
[NSObject out_Hex:checksum andLength:4];
//将校验码附加在地址的原始格式后面
uint8_t last[25];
memcpy(last, originAddress, 21);
memcpy(last+21, checksum, 4);
printf("addchecksum:\n");
[NSObject out_Hex:last andLength:25];
//做base58编码,得到base58check格式的地址
char lsresult[100];
b58enc(lsresult, &len, last, 25);
NSString *base58Address = [NSString stringWithFormat:@"%@", [NSString
stringWithUTF8String:lsresult]];
NSLog(@"\nbase58Address:\n%@",base58Address);