这是Java PBEWithMD5AndDES实现算法。
在不使用任何外部库的情况下,我正在寻找 iOS 平台的 Objective-C 中的完全等价物。接受的解决方案应仅依赖于 iOS SDK 中包含的库。
下面的Java用密码“foo”将“bar”加密为“0WUc+boDvbU=”
new DesEncrypter("foo").encrypt("bar") == "0WUc+boDvbU="
但是 obj-c 代码将密码短语"foo"的"bar"加密为"VRWOhmfj2g8="
NSString* encrypted = [ self encrypt:@"bar"]; == "VRWOhmfj2g8="
我正在寻找的是 obj-c 加密方法将“bar”加密为“0WUc+boDvbU=”,就像 Java 一样。
Java代码:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
public class DesEncrypter {
private Cipher ecipher;
private Cipher dcipher;
private byte[] salt = {(byte) 0x10, (byte) 0x1B, (byte) 0x12, (byte) 0x21, (byte) 0xba, (byte) 0x5e,
(byte) 0x99, (byte) 0x12};
public DesEncrypter(String passphrase) throws Exception {
int iterationCount = 2;
KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
public String encrypt(String str) throws Exception {
return new BASE64Encoder().encode(ecipher.doFinal(str.getBytes())).trim();
}
public String decrypt(String str) throws Exception {
return new String(dcipher.doFinal(new BASE64Decoder().decodeBuffer(str))).trim();
}
}
obj-c 代码
- (NSString*) encrypt:(NSString*)encryptValue {
const void *vplainText;
size_t plainTextBufferSize = [encryptValue length];
vplainText = (const void *) [encryptValue UTF8String];
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
unsigned char salt [] = {0x10,0x1B,0x12,0x21,0xba,0x5e,0x99,0x12};
NSString *key = @"foo";
const void *vkey = (const void *) [key UTF8String];
ccStatus = CCCrypt(kCCEncrypt,kCCAlgorithmDES,kCCOptionPKCS7Padding,vkey,kCCKeySizeDES,salt,vplainText,
plainTextBufferSize,(void *)bufferPtr,bufferPtrSize,&movedBytes);
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *result = [myData base64Encoding];
return result;
}