【发布时间】:2015-09-12 08:41:51
【问题描述】:
到目前为止,我已经尝试过以下代码:
+(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 中。
【问题讨论】:
-
如果“唯一不同的是 INITIALIZATIO_VECTOR”,您将需要使用相同的 iv。此外,密钥和 iv 应该是加密函数的正确大小,否则它们会用 something 填充,这绝不是一个好主意。顺便说一句,通常使用单发
CCHmac函数更容易,请参阅此SO answer,您必须替换kCCHmacAlgSHA1(不应再使用SHA1)并添加BASE64 编码。 -
您需要好好尝试编写代码,如果您在这里发布有问题,SO 不会翻译代码。 SO上有几个例子,检查一下。提示:使用 key 和 iv 的确切长度。 PKCS7Padding 与 PKCS5Padding 相同,但根据定义支持更大的块大小。请注意,Java 会自动决定密钥大小(有点吓人),对于 iOS,您必须指定 128、192 或 256 位密钥大小。
-
@zaph - 很高兴您听到这样友好/有帮助的回复...kCCHmacAlgSHA1 是否也可用于 android!?
-
kCCHmacAlgSHA1是一个 Common Crypto 常量,我怀疑它在 Droid 上有所不同。但是不要使用 HMac SHA1,如果可以选择,至少使用 Hmac SHA256。也不要使用文本作为密钥,如果您必须使用字符串,则使用 PBKFD2 从中创建密钥。以上仅适用于安全性很重要的情况,如果不做任何事情。
标签: android ios objective-c base64 sha