国密SMS4白盒 iOS SDK 文档

国密SMS4白盒密码算法,即将SMS4密钥隐藏在查找表中,加解密的过程就变成查表过程。查找表分加密查找表及解密查找表,用加密查找表加密的结果,只能用解密查找表解密。

注: 白盒加密或解密前,需要使用查找表初始化白盒加密,即需要事先调用wbsms4Setup

接口描述:

/**
 * 白盒密码初始化,用存放了白盒密码查找表的文件初始化白盒密码。
 * 因为查找表被置乱了,所以需要转入用于置乱查找表的SBOX。
 * 即可用加密查找表初始化,也可用解密查找表初始化。
 * @param path 查找表文件路径
 * @param sbox 用于置乱白盒密码查找表的SBOX
 * @throws YiCryptException 计算出错时抛出异常
 */
- (void) wbsms4Setup:(NSString *) path andSBox: (NSData *) sbox;

/**
 * 白盒密码加密,加密的结果只能用拥有解密查找表的白盒进行解密
 * @param paddingMode 填充模式,支持NO_PADDING及PKCS7_PADDING
 * @param input 输入数据
 * @return 输出计算结果
 * @throws YiCryptException 计算出错时抛出异常
 */
- (NSData *) wbsms4Encrypt: (YiPaddingMode) paddingMode andInput: (NSData *) input;

/**
 * 白盒密码解密,只能用于解拥有加密查找表的白盒加密结果
 * @param paddingMode 填充模式,支持NO_PADDING及PKCS7_PADDING
 * @param input 输入数据
 * @return 输出计算结果
 * @throws YiCryptException 计算出错时抛出异常
 */
- (NSData *) wbsms4Decrypt: (YiPaddingMode) paddingMode andInput: (NSData *) input;
接口异常:

ERR_WBSMS4_ILLEGAL_PARAMS: 白盒密码参数非法
ERR_ILLEGAL_INPUT: 输入非法
ERR_WBSMS4_ENCRYPT_FAILED: 白盒加密失败
ERR_WBSMS4_DECRYPT_FAILED: 白盒解密失败
调用示例:

NSMutableString * sboxStr = [NSMutableString new];
[sboxStr appendString:@"3FCA020F2CD08F1E13016B8AAFC103BDBC8C0AD3D89000ABB3B80645E4F7"];
[sboxStr appendString:@"0558EDFDDAB9706C50488DA7849D155E574668861698F87264F6655D92B6A"];
[sboxStr appendString:@"4D4CC5CD928B2242E0866A18B6D25D15B7649A2C2A63D237B543294FA424E"];
[sboxStr appendString:@"C34CEE0B952F9B87FFE37C8239DEC4CBE98E344443363038A50952D56AF38"];
[sboxStr appendString:@"1FBD740BF9EA377BA26D62B177E0421557D0C69E163142AAEB0F5E0A04D3B"];
[sboxStr appendString:@"53836199EBC83CBBB5190D4A5160A97FC993EF9CE52D9F7A078831C7DD1F3"];
[sboxStr appendString:@"3A880275FEC12B15910D2C6207956FC4B3ECD78F45ADB9AFEC0291D89C5F1"];
[sboxStr appendString:@"47711A18AA1BBEB76F0E62ADE78535AC962274751C6EDFF9E2E837674FEAD"];
[sboxStr appendString:@"C913A4111B4F073E6F297CECF"];

NSData * sbox = [[YiSMCore defaultCore] str2Bcd:sboxStr];
NSString *path = [[NSBundle mainBundle] pathForResource: @"encrypt" ofType: @"tb"];
[[YiSMCore defaultCore] wbsms4Setup:path andSBox:sbox];

// NO_PADDING 加密
NSData * wbNoPaddingEnc = [[YiSMCore defaultCore] wbsms4Encrypt:NO_PADDING andInput:[[YiSMCore defaultCore] str2Bcd:@"0123456789abcdeffedcba9876543210"]];

// NO_PADDING 解密
NSData * wbNoPaddingDec = [[YiSMCore defaultCore] wbsms4Decrypt:NO_PADDING andInput:[[YiSMCore defaultCore] str2Bcd:@"9B113BE58CDD28C6F945D72D2A412CA7"]];

// PKCS7_PADDING 加密
NSData * wbPKCS7PaddingEnc = [[YiSMCore defaultCore] wbsms4Encrypt:PKCS7_PADDING andInput:[[YiSMCore defaultCore] str2Bcd:@"616263"]];

// PKCS7_PADDING 解密
NSData * wbPKCS7PaddingDec = [[YiSMCore defaultCore] wbsms4Decrypt:PKCS7_PADDING andInput:[[YiSMCore defaultCore] str2Bcd:@"D9A477577719D8311E779105051C0943"]];
输出示例:

wbNoPaddingEnc: 79CDA104497A82D58E6BF09267FCC60B

wbNoPaddingDec: 0123456789ABCDEFFEDCBA9876543210

wbPKCS7PaddingEnc: FA17CCF37795597A75A95A49915B8296

wbPKCS7PaddingDec: 616263