簡體   English   中英

AES加密Java到iOs - 使用密碼,iv和salt

[英]AES Encryption Java to iOs - With password, iv and salt

我正在為三個平台(Android,ios和WP8)開發應用程序。 此應用程序與服務器連接並使用AES進行安全性。

我准備好了Android和Windows Phone的測試版本,並且用android生成的代碼(在base64中)用wp代碼解碼,相反。

但是,在iOs上我得到了相同的SALT,KEY和IV的其他響應。 這是我的android代碼:

public static SecretKeySpec generateKey(char[] password, byte[] salt) throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password, salt, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        return secret;
    }

public static Map encrypt(String cleartext, byte[] iv, SecretKeySpec secret) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    // If the IvParameterSpec argument is omitted (null), a new IV will be
    // created
    cipher.init(Cipher.ENCRYPT_MODE, secret, iv == null ? null : new IvParameterSpec(iv));
    AlgorithmParameters params = cipher.getParameters();
    byte[] usediv = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] ciphertext = cipher.doFinal(cleartext.getBytes("UTF-8"));
    Map result = new HashMap();
    result.put(IV, usediv);
    result.put(CIPHERTEXT, ciphertext);
    return result;
}


public static String decrypt(byte[] ciphertext, byte[] iv, SecretKeySpec secret) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
    return plaintext;
}

public static void main(String arg) throws Exception {
    byte[] salt = new byte[] { -11, 84, 126, 65, -87, -104, 120, 33, -89, 19, 57, -6, -27, -19, -101, 107 };



    byte[] interop_iv = Base64.decode("xxxxxxxxxxxxxxx==", Base64.DEFAULT);
    byte[] iv = null;
    byte[] ciphertext;
    SecretKeySpec secret; 
    secret = generateKey("xxxxxxxxxxxxxxx".toCharArray(), salt);
    Map result = encrypt(arg, iv, secret);
    ciphertext = (byte[]) result.get(CIPHERTEXT);
    iv = (byte[]) result.get(IV);
    System.out.println("Cipher text:" + Base64.encode(ciphertext, Base64.DEFAULT));
    System.out.println("IV:" + Base64.encode(iv, Base64.DEFAULT) + " (" + iv.length + "bytes)");
    System.out.println("Key:" + Base64.encode(secret.getEncoded(), Base64.DEFAULT));
    System.out.println("Deciphered: " + decrypt(ciphertext, iv, secret));

    // Interop demonstration. Using a fixed IV that is used in the C#
    // example
    result = encrypt(arg, interop_iv, secret);
    ciphertext = (byte[]) result.get(CIPHERTEXT);
    iv = (byte[]) result.get(IV);

    String text = Base64.encodeToString(ciphertext, Base64.DEFAULT);

    System.out.println();
    System.out.println("--------------------------------");
    System.out.println("Interop test - using a static IV");
    System.out.println("The data below should be used to retrieve the secret message by the receiver");
    System.out.println("Cipher text:  " + text);
    System.out.println("IV:           " + Base64.encodeToString(iv, Base64.DEFAULT));
    decrypt(Base64.decode(text, Base64.DEFAULT), iv, secret);
}

這是我的ios代碼......我在Android代碼中設置了靜態IV和SALT但是沒找到:

- (NSData*)encryptData:(NSData*)data :(NSData*)key :(NSData*)iv
{
    size_t bufferSize = [data length]*2;
    void *buffer = malloc(bufferSize);
    size_t encryptedSize = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          [key bytes], [key length], [iv bytes], [data bytes], [data length],
                                          buffer, bufferSize, &encryptedSize);
    if (cryptStatus == kCCSuccess)
        return [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
    else
        free(buffer);
    return NULL;
}

// ===================

- (NSData *)encryptedDataForData:(NSData *)data
                        password:(NSString *)password
                              iv:(NSData *)iv
                            salt:(NSData *)salt
                           error:(NSError *)error {

    NSData *key = [self AESKeyForPassword:password salt:salt];
    size_t outLength = 0;
    NSMutableData *
    cipherData = [NSMutableData dataWithLength:data.length +
                  kAlgorithmBlockSize];

    const unsigned char iv2[] = {68, 55, -98, -59, 22, -25, 55, -50, -101, -25, 53, 30, 42, -20, -107, 4};

    CCCryptorStatus
    result = CCCrypt(kCCEncrypt, // operation
                     kAlgorithm, // Algorithm
                     kCCOptionPKCS7Padding, // options
                     key.bytes, // key
                     key.length, // keylength
                     iv2,// iv
                     data.bytes, // dataIn
                     data.length, // dataInLength,
                     cipherData.mutableBytes, // dataOut
                     cipherData.length, // dataOutAvailable
                     &outLength); // dataOutMoved

    if (result == kCCSuccess) {
        cipherData.length = outLength;
    }
    else {
        if (error) {
            error = [NSError errorWithDomain:kRNCryptManagerErrorDomain
                                         code:result
                                     userInfo:nil];
        }
        return nil;
    }

    return cipherData;
}

// ===================

- (NSData *)randomDataOfLength:(size_t)length {
    NSMutableData *data = [NSMutableData dataWithLength:length];

    int result = SecRandomCopyBytes(kSecRandomDefault,
                                    length,
                                    data.mutableBytes);
    NSAssert(result == 0, @"Unable to generate random bytes: %d",
             errno);

    return data;
}

// ===================

// Replace this with a 10,000 hash calls if you don't have CCKeyDerivationPBKDF
- (NSData *)AESKeyForPassword:(NSString *)password
                         salt:(NSData *)salt {
    NSMutableData *
    derivedKey = [NSMutableData dataWithLength:kAlgorithmKeySize];

    int
    result = CCKeyDerivationPBKDF(kCCPBKDF2,            // algorithm
                                  password.UTF8String,  // password
                                  [password lengthOfBytesUsingEncoding:NSUTF8StringEncoding],  // passwordLength
                                  salt.bytes,           // salt
                                  salt.length,          // saltLen
                                  kCCPRFHmacAlgSHA1,    // PRF
                                  kPBKDFRounds,         // rounds
                                  derivedKey.mutableBytes, // derivedKey
                                  derivedKey.length); // derivedKeyLen
    // Do not log password here
    NSAssert(result == kCCSuccess,
             @"Unable to create AES key for password: %d", result);

    return derivedKey;
}

我將數據轉換為base64如下:

NSString* dataStr = [encryptedData base64EncodedStringWithOptions:0];
    NSLog(@"%@", dataStr);

最后我在android和wp上使用這個代碼: http//www.dfg-team.com/en/secure-data-on-windows-phone-with-aes-256-encryption/

在過去,我已經遇到了像你這樣的問題。 我剛剛使用這個庫找到了解決方案: https//github.com/dev5tec/FBEncryptor

別忘了在FBEncryptorAES.h文件中驗證算法配置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM