SHA256 with RSA Signing in iOS and verfying in JAVA

  Kiến thức lập trình

I tried creating private, public key pair in Swift and created signature for a text in iOS and tried to verify the same in JAVA but it is always FALSE.

Below is Swift Code used for Creating KEy value pair and Signature

 let tag = "com.example.keys.mykey".data(using: .utf8)!
        let attributes: [String: Any] = [
            kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
            kSecAttrKeySizeInBits as String:      2048,
            kSecPrivateKeyAttrs as String: [
                kSecAttrIsPermanent as String:    true,
                kSecAttrApplicationTag as String: tag
            ]
        ]

        var error: Unmanaged<CFError>?
        guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
            print("Error creating key pair: ((error!.takeRetainedValue() as Error).localizedDescription)")
            return
        }

        guard let publicKey = SecKeyCopyPublicKey(privateKey) else {
            print("Error retrieving public key")
            return
        }

        // Sign data
        let message = "Hello, World!"
        let messageData = message.data(using: .utf8)!

        guard let signature = SecKeyCreateSignature(privateKey,
                                                    .rsaSignatureMessagePKCS1v15SHA256,
                                                    messageData as CFData,
                                                    &error) as Data? else {
            print("Error signing data: ((error!.takeRetainedValue() as Error).localizedDescription)")
            return
        }

        print("Signature: (signature.base64EncodedString())")

        // Export the public key to share with Java
//        var error: Unmanaged<CFError>?
        if let cfdata = SecKeyCopyExternalRepresentation(publicKey, &error) {
            let data: Data = cfdata as Data
            print("Public Key: (data.base64EncodedString())")
        } else {
            print("Error exporting public key: ((error!.takeRetainedValue() as Error).localizedDescription)")
        }

And below is the JAVA code for verifying

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class SignatureVerifier {
    public static void main(String[] args) {
        try {
            // The original message that was signed with the private key in Swift
            String originalMessage = "Hello, World!";
            byte[] messageBytes = originalMessage.getBytes("UTF-8");

            // // Signature and public key received from Swift
            String publicKeyBase64 = "MIIBCgKCAQEApVBIkx9xk6WZ77WmGB0Ie3g1WrvgOEO6nMdCIWZ5/pRyrB2qgrkg72B7R8NS8djjBAyVB7pHoijP7juw93/wk6sE4/+oMhGxIN65QHKZWkohcVSmkEuAVqmiHOX3uxAlnKncRWhAGGVQyIdQMIKso3yGxvf0yujCY9lUmmXmvbluu1WF4zDVkLvDQ5x2DAPDh0Zv0W1f+Mb0FX661Wpsx7p71wdB2MS8DJvIwwOarY3MINbzLE2gmXAjsauiql2NIFo7Nj29tUyhI3pujMqjJ38+l3McAUxagfDD0xUwnSFmoUgqu9P+ood9kOMbcjYLvGixBKznw4nMn/sqtq3yswIDAQAB";
            String signatureBase64 = "IJTkWLpXn1MMcuVd+9p+UFQcU6NBy/aXDAWObkg3SjBgnYXlh9/2TFIBB/+wuot8Jh2pewPH7GhHNxYrS/mvVpZgU2ic8txnwbb/ZeVqXEhAkDdV53gH5J2Ob9S8vfl3bS3TgH2vuBruJn8Eak6nU92YEs4fGfcZ/Yo/3hfMYjyp3zXHvNhOdTa8xYo4RMDMgTs9bKzQ/dGK/LlxUMpZI0ipytwZs6R18dg5mvHL37y824/zz4mMwZAujw7NjaRbPW6XUpdaIq+WgrPQITt9Fb44OE3rYWpuG8CrurwiQgRxTNCM/njWBlvIFo+ORMqwaB5uWi7BvGx0yuFZ4lKRCA==";
            
 
            // Decode the public key and signature
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyBase64);
            byte[] signatureBytes = Base64.getDecoder().decode(signatureBase64);

            // Reconstruct the public key
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

            // Verify the signature
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(publicKey);
            signature.update(messageBytes);

            boolean isVerified = signature.verify(signatureBytes);
            System.out.println("Signature verified: " + isVerified);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tried with this site https://8gwifi.org/RSAFunctionality?rsasignverifyfunctions=rsasignverifyfunctions&keysize=512#google_vignette
to create public, private key and try with JAVA code, it is getting verified but the code from iOS is not getting verified

LEAVE A COMMENT