首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >目标C中用CCCryptor解密Go中CFB加密的数据

目标C中用CCCryptor解密Go中CFB加密的数据
EN

Stack Overflow用户
提问于 2015-09-21 03:25:31
回答 1查看 905关注 0票数 0

我做这个工作已经很长时间了,但是我被困住了。

我正在编写一个iOS应用程序,将AES加密的数据从Go服务器端应用程序中提取出来,并对其进行解密。我在iOS端使用iOS进行解密。然而,为了我的生命,我不能把明文公之于众。有一个可以工作的Java/Android实现,它可以在Go端解密,所以我非常肯定这与我的CCCryptor设置有关。

在解密时,我实际上获得了0的成功状态,但是接受输出并执行NSString initWithBytes会给出一个空字符串。

注意:我只是在写iOS方面。

加密的Go代码:

代码语言:javascript
复制
func encrypt(key, text []byte) []byte {

  block, err := aes.NewCipher(key)
  if err != nil {
    panic(err)
  }

  b := encodeBase64(text)
  ciphertext := make([]byte, aes.BlockSize+len(b))
  iv := ciphertext[:aes.BlockSize]
  if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    panic(err)
  }

  cfb := cipher.NewCFBEncrypter(block, iv)

  cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))

  return ciphertext
}

目标-解密的C代码

代码语言:javascript
复制
+ (NSData *)decrypt:(NSData*)data withPassword:(NSString*)password{


NSData * key = [password dataUsingEncoding:NSUTF8StringEncoding];

size_t dataLength   = [data length] - kCCBlockSizeAES128;
NSData *iv          = [data subdataWithRange:NSMakeRange(0, kCCBlockSizeAES128)];
NSData *encrypted   = [data subdataWithRange:NSMakeRange(kCCBlockSizeAES128, dataLength)];

//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
//    size_t bufferSize = dataLength + kCCBlockSizeAES128;
//    void *buffer = malloc(dataLength);
NSMutableData *ret = [NSMutableData dataWithLength:dataLength + kCCBlockSizeAES128];

size_t numBytesDecrypted = 0;
CCCryptorStatus status = CCCrypt(kCCDecrypt, kCCAlgorithmAES,
                                 0x0000, // change to 0 solve the problem
                                 [key bytes],
                                 kCCKeySizeAES256,
                                 [iv bytes],
                                 [encrypted bytes], dataLength, /* input */
                                 [ret mutableBytes], [ret length], /* output */
                                 &numBytesDecrypted
                                 );

NSLog(@"err: %d", status);
NSLog(@"dataLength: %d, num: %d", (int)dataLength, (int)numBytesDecrypted);
if (status == kCCSuccess) {
    //the returned NSData takes ownership of the buffer and will free it on deallocation
    return ret;
}

//    free(buffer); //free the buffer;
return nil;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-21 15:17:33

我建议使用RNCryptor,有一个iOS和一个实现可用。

RNCryptor结合了满足您需要的所有必要的加密原语,包括:

  • AES-256加密(高级加密标准)
  • CBC模式(密码块链接)
  • 密码扩展与PBKDF2 (基于密码的密钥派生函数2)
  • 密码盐析
  • 随机IV (初始化向量)
  • 加密-然后-哈希HMAC (认证)

它已得到广泛部署和审查。

所有这一切都很容易使密码学错误,使用RNCryptor将避免潜在的陷阱。

如果我有密码学的需要,我会用它的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32686871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档