iOS和Android之间的RSA加密解密

时间:2014-10-15 06:14:36

标签: android ios encryption rsa

我在iOS端生成了RSA密钥对(iOSPrivate& iOSPublic密钥)并将公钥传递给Android,然后在Android Side中使用PlainText加密iOSPublic Key。现在,再次将加密密码传递回iOS,并使用iOS端的iosPrivate密钥解密此加密密码。我获得了PlainText 回来。

但是,当我在Android端生成RSA密钥对(And_Private& And_Public Key)并将公钥传递给iOS时,然后在iOS端使用PlainText加密And_Public密钥,现在再次将加密密码传递回Android,并使用Android Side中的And_Private密钥解密此加密密码 无法解密它。

我在两端都使用了以下代码片段:

的iOS //加密

- (NSString *)encrypt:(NSString *)plainText
                  key:(NSString *)key
                error:(BDError *)error
{

    if (!plainText)
    {
        [error addErrorWithType:BDCryptoErrorEncrypt
                     errorClass:[BDCryptorError class]];

        return nil;
    }

    [self setPublicKey:key
                   tag:[self publicKeyIdentifier]
                 error:error];

    SecKeyRef publicKey = [self keyRefWithTag:[self publicKeyIdentifier]
                                        error:error];

    if ([BDError error:error
     containsErrorType:BDCryptoErrorRSACopyKey
            errorClass:[BDCryptorError class]])
    {
        return nil;
    }

    uint8_t *nonce = (uint8_t *)[plainText UTF8String];
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = malloc(cipherBufferSize);

    if (cipherBufferSize < sizeof(nonce))
    {
        if (publicKey)
        {
            CFRelease(publicKey);
        }

        free(cipherBuffer);

        [error addErrorWithType:BDCryptoErrorRSATextLength
                     errorClass:[BDCryptorError class]];

        return nil;
    }
    OSStatus secStatus = SecKeyEncrypt(publicKey,
                                       kSecPaddingNone,
                                       nonce,
                                       strlen((char *)nonce) + 1,
                                       &cipherBuffer[0],
                                       &cipherBufferSize);

    if (secStatus != noErr)
    {
        [error addErrorWithType:BDCryptoErrorEncrypt
                     errorClass:[BDCryptorError class]];

        return nil;
    }

    NSData *encryptedData = [NSData dataWithBytes:cipherBuffer
                                           length:cipherBufferSize];

    if (publicKey)
    {
        CFRelease(publicKey);
    }
    free(cipherBuffer);

    NSString *result = [encryptedData base64EncodedString];

    return result;
}

//解密

- (NSString *)decrypt:(NSString *)cipherText
                  key:(NSString *)key
                error:(BDError *)error
{
    if (!cipherText)
    {
        [error addErrorWithType:BDCryptoErrorDecrypt
                     errorClass:[BDCryptorError class]];

        return nil;
    }

    [self setPrivateKey:key
                    tag:[self privateKeyIdentifier]
                  error:error];

    NSMutableDictionary *keyQueryDictionary = [self keyQueryDictionary:[self privateKeyIdentifier]];
    [keyQueryDictionary setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];

    SecKeyRef privateKey = [self keyRefWithTag:[self privateKeyIdentifier]
                                         error:error];

    if ([BDError error:error
     containsErrorType:BDCryptoErrorRSACopyKey
            errorClass:[BDCryptorError class]])
    {
        return nil;
    }

    size_t plainBufferSize = SecKeyGetBlockSize(privateKey);
    uint8_t *plainBuffer = malloc(plainBufferSize);

    NSData *incomingData = [cipherText base64DecodedData];
    uint8_t *cipherBuffer = (uint8_t*)[incomingData bytes];
    size_t cipherBufferSize = SecKeyGetBlockSize(privateKey);

    if (plainBufferSize < cipherBufferSize)
    {
        if (privateKey)
        {
            CFRelease(privateKey);
        }

        free(plainBuffer);

        [error addErrorWithType:BDCryptoErrorRSATextLength
                     errorClass:[BDCryptorError class]];

        return nil;
    }
    OSStatus secStatus = SecKeyDecrypt(privateKey,
                                       kSecPaddingNone,
                                       cipherBuffer,
                                       cipherBufferSize,
                                       plainBuffer,
                                       &plainBufferSize);

    if (secStatus != noErr)
    {
        [error addErrorWithType:BDCryptoErrorDecrypt
                     errorClass:[BDCryptorError class]];

        return nil;
    }

    NSString *decryptedString = [[NSString alloc] initWithBytes:plainBuffer
                                                         length:plainBufferSize
                                                       encoding:NSUTF8StringEncoding];

    free(plainBuffer);

    if (privateKey)
    {
        CFRelease(privateKey);
    }

    return decryptedString;
}

的Android

//加密

   public byte[] RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    kp = kpg.genKeyPair();
    publicKey = kp.getPublic();
    privateKey = kp.getPrivate();

    cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    encryptedBytes = cipher.doFinal(plain.getBytes());
    System.out.println("EEncrypted?????" + org.apache.commons.codec.binary.Hex.encodeHexString(encryptedBytes));
    return encryptedBytes;
}

//解密

public String RSADecrypt(final byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, privateKey);
    decryptedBytes = cipher1.doFinal(encryptedBytes);
    decrypted = new String(decryptedBytes);
    System.out.println("DDecrypted?????" + decrypted);
    return decrypted;
}

0 个答案:

没有答案