简体   繁体   中英

Can i use public key which is generated from iOS, in c# code to encrypt data and again decry-pt the encrypted data(using private key) in iOS?

I have generated key pair in iOS and when i decrypt the data which is encrypted using public key in c# code i am receiving below error....

"Error Domain=NSOSStatusErrorDomain Code=-50 "<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 1024 bits, addr: 0x60000269ce20>: sign - input buffer bad size (144 bytes)" UserInfo={NSDescription=<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 1024 bits, addr: 0x60000269ce20>: sign - input buffer bad size (144 bytes)}"

I am using key size of 1024 and using rsaEncryptionPKCS1 encryption.....

iOS code ---

**

private func createSecureKeyPair(_ keyTag: String, _ keyType :KeyType = .publicKey) -> Data? {
        // private key parameters
        let privateKeyParams: [String: AnyObject] = [
            kSecAttrIsPermanent as String: true as AnyObject,
            kSecAttrCanDecrypt as String: true as AnyObject,
            kSecAttrApplicationTag as String: keyTag as AnyObject,
        ]
        // private key parameters
        let publicKeyParams: [String: AnyObject] = [
            kSecAttrApplicationTag as String: keyTag as AnyObject,
            kSecAttrIsPermanent as String: true as AnyObject
        ]        
        // global parameters for our key generation
        let parameters: [String: AnyObject] = [
            kSecAttrKeyType as String:          kSecAttrKeyTypeRSA as AnyObject,
            kSecAttrKeySizeInBits as String:    1024 as AnyObject,
            kSecPublicKeyAttrs as String:       publicKeyParams as AnyObject,
            kSecPrivateKeyAttrs as String:      privateKeyParams as AnyObject,
        ]
        
        var pubKey, privKey: SecKey?
        let status = SecKeyGeneratePair(parameters as CFDictionary, &pubKey, &privKey)
        if status == errSecSuccess {
            print("Successfully generated keypair!\nPrivate key: \(String(describing: privKey))\nPublic key: \(String(describing: pubKey))")
            return self.getKeyData(keyTag,keyType)
        } else {
            print("Error generating keypair: \(status)")
            return nil
        }
    }

func encryptData(messageData: Data, publicKeySec: SecKey) -> Data? {     
        guard let encryptData = SecKeyCreateEncryptedData(
            publicKeySec,
            SecKeyAlgorithm.rsaEncryptionPKCS1,
            messageData as CFData,
            nil) else {
                print("Encryption Error")
                return nil
            }
        print(encryptData)
        return encryptData as Data
    }

func decryptData(messageData : Data, privateKeySec: SecKey) -> Data? {
        guard let decryptData = SecKeyCreateDecryptedData(
            privateKeySec,
            SecKeyAlgorithm.rsaEncryptionPKCS1,
            messageData as CFData,
            nil) else {
                print("Decryption Error")
                return nil
        }
        return decryptData as Data
    }


---------------c# Code

public static string RSAEncrypt(string plainData, string publicKeyXml)
        {
            using (RSA rsa = RSA.Create())
            {
                try
                {
                    rsa.KeySize = 1024;
                    RSAParameters parameter = FromXmlString(rsa, publicKeyXml);
                    rsa.ImportParameters(parameter);
                    byte[] encryptedBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plainData), RSAEncryptionPadding.Pkcs1);
                    return Convert.ToBase64String(encryptedBytes);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
        }

I want to export public key from iOS in standard format which can be extracted in c# without using any Nuget package...any help is much appreciated.


One solution that I found is to use bouncy castle Nuget package in C# to import RSA public key than encrypt data in c#...


public static string RSAEncryptiOS(string plainData, string publicKeyiOS)
        {
            try
            {
                byte[] publicKeyBytes = Convert.FromBase64String(publicKeyiOS);

                var stream = new MemoryStream(publicKeyBytes);
                Asn1Object asn1Object = Asn1Object.FromStream(stream);
                Asn1Encodable asn1Sequence = asn1Object;

                AlgorithmIdentifier algorithmIdentifier = new
                AlgorithmIdentifier(PkcsObjectIdentifiers.IdRsaesOaep);

                SubjectPublicKeyInfo subjectPublicKeyInfo = new
                SubjectPublicKeyInfo(algorithmIdentifier, asn1Sequence);

                AsymmetricKeyParameter asymmetricKeyParameter2 =
                PublicKeyFactory.CreateKey(subjectPublicKeyInfo);

                RsaKeyParameters rsaKeyParameters =
                (RsaKeyParameters)asymmetricKeyParameter2;
                RSAParameters rsaParameters = new RSAParameters();
                rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(rsaParameters);
                //string test = "Hello World 2020";
                byte[] encbyte = rsa.Encrypt(Encoding.UTF8.GetBytes(plainData), RSAEncryptionPadding.Pkcs1);
                return Convert.ToBase64String(encbyte);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            
        }
***

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM