实现Base 64和SHA

时间:2015-09-12 08:41:52

标签: android ios objective-c base64 sha

到目前为止,我尝试过以下代码:

+(NSString*)encodeString:(NSString*)origString{
    /* Here we can choose the algorithm */
    NSData *keyData = [@"secret_key" dataUsingEncoding:NSUTF8StringEncoding];

    NSData *textData = [origString dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};

    CCHmacContext hmacContext;
    CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length);
    CCHmacUpdate(&hmacContext, textData.bytes, textData.length);
    CCHmacFinal(&hmacContext, digest);

    /* out is HMAC */
    NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];

    /* resultString is Base64 encoded HMAC */
    NSString *resultString = [out base64EncodedString];
    return resultString;
}

这样可以得到正确的结果。但我的android和后端合作伙伴希望我将以下代码克隆到objective-c:

private String encryptString(String origString) {
    String encryptedString = "";
    Cipher cipher = null;
    byte[] encoded = null;
    byte[] rawEnc =null;
    try {
        //Code which is working
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes("UTF-8"), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(INITIALIZATIO_VECTOR.getBytes("UTF-8")));
        rawEnc = cipher.doFinal(origString.getBytes("UTF-8"));
        encoded = Base64.encodeBase64(rawEnc);
        encryptedString = new String(encoded, "UTF-8");

    } catch (NoSuchAlgorithmException e) {
        System.out.println("No Such Algorithm Exception:" + e.getMessage());
    } catch (NoSuchProviderException e) {
        System.out.println("No Such Provider Exception:" + e.getMessage());
    } catch (NoSuchPaddingException e) {
        System.out.println("No Such Padding Exception:" + e.getMessage());
    } catch (InvalidKeyException | InvalidAlgorithmParameterException
             | UnsupportedEncodingException e) {
        System.out.println("Exception:" + e.getMessage());
    } catch (Exception e) {
        System.out.println("Exception:" + e.getMessage());
    }
    return encryptedString;
}
private static final String SECRET_KEY = "secret_key";
private static final String INITIALIZATIO_VECTOR = "123456";

}

android的输出与iOS不同,并且是后端开发人员的要求。所以,我必须根据他们的意见转换代码。

唯一不同的是INITIALIZATIO_VECTOR

我想在Objective-C中使用上面的代码。

1 个答案:

答案 0 :(得分:1)

该问题包含:"实施Base 64"。

iOS上没有必要,只需使用Apple NSData Base64 API:

  

使用给定选项从接收者的内容创建Base-64编码的NSString:

- base64EncodedStringWithOptions:
  

返回使用给定的Base-64编码数据初始化的数据对象:

- initWithBase64EncodedData:options:
  

返回使用给定的Base-64编码字符串初始化的数据对象:

- initWithBase64EncodedString:options: