Impossible de déchiffrer les données AES à l'aide d'Obj-C qui ont été chiffrées à l'aide de Java

Gruntcakes

Je suis bloqué en essayant de déchiffrer certaines données cryptées AES envoyées par un serveur à mon application.

Afin de dissiper le problème, j'ai écrit un petit programme java qui émule ce que fait le serveur. Il crypte certaines données de test en utilisant AES puis les encode en Base64:

AesCipherService cipherService  = new AesCipherService();
cipherService.setKeySize(128);

String stringKey = "2EE1F10212ADD4BE";
byte[] keyAsBytes =  stringKey.getBytes();

String text = "text to encrypt";
byte[] encryptedBytes    = cipherService.encrypt(text.getBytes(), keyAsBytes).getBytes();
String base64String      = Base64.encodeToString(encryptedBytes);
System.out.println(base64String);

// Reverse the process to check can retrieve "text to encrypt":
byte[] bytesToDecode = Base64.decode(base64String);
byte[] decryptedBytes = cipherService.decrypt(bytesToDecode, keyAsBytes).getBytes();         
String decryptedString = new String(decryptedBytes);   
System.out.println(decryptedString);

Lorsqu'il est exécuté, c'est la sortie:

R5UBpP30YjX9Ae2HoPb2Rrfi5rQJY2d0ac1 + zaIX5A4 =

texte à crypter

Je peux donc chiffrer avec succès les données, les imprimer. Ensuite, si je le déchiffre, le texte original est affiché, donc tout ici fonctionne correctement.

Voici maintenant mon code Obj-C où j'essaye de décrypter les données chiffrées à partir du code Java. J'ai copié / collé les données cryptées de la fenêtre de sortie de l'EDI NetBeans en tant que données source du contenu obj-c à décrypter:

- (void) decryptData
{
    NSData* dataToDecrypt       = [[NSData alloc] initWithBase64EncodedString: @"R5UBpP30YjX9Ae2HoPb2Rrfi5rQJY2d0ac1+zaIX5A4="  options: 0];
    NSString* key               = @"2EE1F10212ADD4BE";

    char keyPtr[kCCKeySizeAES128];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    NSUInteger dataLength = [dataToDecrypt length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          keyPtr,
                                          [dataToDecrypt bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSLog(@"Success");
        NSData* unencryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
        Byte *unencryptedAsBytes = (Byte*)malloc(unencryptedData.length);
        memcpy(unencryptedAsBytes, [unencryptedData  bytes], unencryptedData.length);
        NSString *decryptedString = [NSString stringWithUTF8String:[unencryptedData bytes]];
        NSLog(@"%@", decryptedString);
    }
}

Quand ceci est exécuté, le statut est kCCSuccess et numBytesDecrypted est 32 (identique à dataLength) mais la chaîne déchiffrée n'est pas "text to encrypt", decryptedString est nul et si je po unencryptedAsBytes dans la console de Xcode, il affiche ceci:

"\ aY | \ 376 \ 347cD * \ 320NC \ x14 \ x91C \ x88 \ 301 \ 341z \ xaca \ x11 \ 371

Une idée de quel est le problème ici?

zaph

Le code de cryptage Java génère un IV aléatoire et préfixe le crypté avec lui. Afin de décrypter l'IV est séparé du crypté.

En hexadécimal:

key:       32454531463130323132414444344245  
iv:        479501A4FDF46235FD01ED87A0F6F646 (first 16 binary bytes of the full encryption)  
encrypted: B7E2E6B40963677469CD7ECDA217E40E (rest of binary bytes of the full encryption)  
decrypted: 7465787420746F20656E6372797074

Code:

NSData* fullEncrypted       = [[NSData alloc] initWithBase64EncodedString: @"R5UBpP30YjX9Ae2HoPb2Rrfi5rQJY2d0ac1+zaIX5A4="  options: 0];
NSData *ivData = [fullEncrypted subdataWithRange:NSMakeRange(0, kCCBlockSizeAES128)];
NSData *encryptedData = [fullEncrypted subdataWithRange:NSMakeRange(kCCBlockSizeAES128, fullEncrypted.length-kCCBlockSizeAES128)];
NSLog(@"ivData:          %@", ivData);
NSLog(@"encryptedData:   %@", encryptedData);

NSData *keyData = [@"2EE1F10212ADD4BE" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"keyData:         %@", keyData);

NSMutableData *unencryptedData = [NSMutableData dataWithLength:encryptedData.length];
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                      kCCAlgorithmAES,
                                      kCCOptionPKCS7Padding,
                                      keyData.bytes, keyData.length,
                                      ivData.bytes,
                                      encryptedData.bytes, encryptedData.length,
                                      unencryptedData.mutableBytes, unencryptedData.length,
                                      &numBytesDecrypted);
if (cryptStatus == kCCSuccess) {
    NSLog(@"Success");

    unencryptedData.length = numBytesDecrypted;
    NSLog(@"unencryptedData: %@", unencryptedData);

    NSString *decryptedString = [[NSString alloc] initWithData:unencryptedData encoding:NSUTF8StringEncoding];
    NSLog(@"decryptedString: %@", decryptedString);
}

Production:

ivData:          479501a4 fdf46235 fd01ed87 a0f6f646  
encryptedData:   b7e2e6b4 09636774 69cd7ecd a217e40e  
keyData:         32454531 46313032 31324144 44344245  
Success  
unencryptedData: 74657874 20746f20 656e6372 79707400  
decryptedString: text to encrypt  

Cet article est collecté sur Internet, veuillez indiquer la source lors de la réimpression.

En cas d'infraction, veuillez [email protected] Supprimer.

modifier le
0

laisse moi dire quelques mots

0commentaires
connexionAprès avoir participé à la revue

Articles connexes

TOP liste

  1. 1

    comment afficher un bouton au-dessus d'un autre élément ?

  2. 2

    impossible d'obtenir l'image d'arrière-plan en plein écran dans reactjs

  3. 3

    Je continue à obtenir l'objet 'WSGIRequest' n'a pas d'attribut 'Get' sur django

  4. 4

    comment supprimer "compte de connexion google" à des fins de développement - actions sur google

  5. 5

    Conversion double en BigDecimal en Java

  6. 6

    Impossible d'accéder à la vue personnalisée pendant le test de l'interface utilisateur dans XCode

  7. 7

    Algorithme: diviser de manière optimale une chaîne en 3 sous-chaînes

  8. 8

    Passer la taille d'un tableau 2D à une fonction ?

  9. 9

    Comment obtenir l'intégration contextuelle d'une phrase dans une phrase à l'aide de BERT ?

  10. 10

    Comment changer le navigateur par défaut en Microsoft Edge pour Jupyter Notebook sous Windows 10 ?

  11. 11

    CSS: before ne fonctionne pas sur certains éléments,: after fonctionne très bien

  12. 12

    Comment créer un bot à compte à rebours dans Discord en utilisant Python

  13. 13

    Comment ajouter une entrée à une table de base de données pour une combinaison de deux tables

  14. 14

    Exporter la table de l'arborescence vers CSV avec mise en forme

  15. 15

    Comment activer le message Pylint "too-many-locals" dans VS Code?

  16. 16

    Créer un système Buzzer à l'aide de python

  17. 17

    Spring @RequestParam DateTime format comme ISO 8601 Date Heure facultative

  18. 18

    Empêcher l'allocation de mémoire dans la génération de combinaison récursive

  19. 19

    Déplacement des moindres carrés d'ajustement pour les déplacements de points ayant des problèmes

  20. 20

    Comment choisir le nombre de fragments et de répliques Elasticsearch

  21. 21

    Microsoft.WebApplication.targets

chaudétiquette

Archive