Apple Pay - decrypt payment data - ios

I am trying to decrypt paymentData property of PKPaymentToken object upon a successful Apple Pay authorization.
I am trying to follow the instruction here, but I am stuck on step 2 of the decryption steps, which says:
Use the value of the publicKeyHash key to determine which merchant
public key was used by Apple, and then retrieve the corresponding
merchant public key certificate and private key.
How do I do that?
Please advise.
Thanks!

Here's how to compute the publicKeyHash in Ruby, given the Apple Pay certificate file downloaded from the Apple Developer Center.
require "base64"
require "digest"
require "openssl"
# set cert_file = path to the downloaded Apple Pay .cer file
cert = OpenSSL::X509::Certificate.new(File.read(cert_file))
# strip off the "-----BEGIN PUBLIC KEY-----" line at the start of the string
pem = cert.public_key.to_pem.split("\n").drop(1)
# strip off the "-----END PUBLIC KEY-----" line at the end of the string
pem = pem.take(pem.length - 1)
decoded = Base64.decode64(pem.join)
public_key_hash = Digest::SHA256.base64digest(decoded)

The value of the publicKeyHash field is...a hash of your public key. As per the documentation, it's a SHA-256 hash of the X.509 encoded public key bytes of the merchant's certificate. You use this to determine which merchant identifier was used to sign the payment data (you probably only have one merchant identifier, in which case you'll already know which one is being used).

Related

How can I do public key pinning in Flutter?

I want to the pin the public key of my server so that any request made to the server has to have that public key (this is to prevent proxies like Charles sniffing the data).
I had done something similar in Android with Volley.
How can I do the same with Flutter?
Create your client with a SecurityContext with no trusted roots to force the bad certificate callback, even for a good certificate.
SecurityContext(withTrustedRoots: false);
In the bad certificate callback, parse the DER encoded certificate using the asn1lib package. For example:
ASN1Parser p = ASN1Parser(der);
ASN1Sequence signedCert = p.nextObject() as ASN1Sequence;
ASN1Sequence cert = signedCert.elements[0] as ASN1Sequence;
ASN1Sequence pubKeyElement = cert.elements[6] as ASN1Sequence;
ASN1BitString pubKeyBits = pubKeyElement.elements[1] as ASN1BitString;
List<int> encodedPubKey = pubKeyBits.stringValue;
// could stop here and compare the encoded key parts, or...
// parse them into their modulus/exponent parts, and test those
// (assumes RSA public key)
ASN1Parser rsaParser = ASN1Parser(encodedPubKey);
ASN1Sequence keySeq = rsaParser.nextObject() as ASN1Sequence;
ASN1Integer modulus = keySeq.elements[0] as ASN1Integer;
ASN1Integer exponent = keySeq.elements[1] as ASN1Integer;
print(modulus.valueAsBigInteger);
print(exponent);
Key rotation reduces risk. When an attacker obtains an old server hard drive or backup file and gets an old server private key from it, they cannot impersonate the current server if the key has been rotated. Therefore always generate a new key when updating certificates. Configure the client to trust the old key and the new key. Wait for your users to update to the new version of the client. Then deploy the new key to your servers. Then you can remove the old key from the client.
Server key pinning is only needed if you're not rotating keys. That's bad security practice.
You should do certificate pinning with rotation. I have added example code in How to do SSL pinning via self generated signed certificates in flutter?

Apple MusicKit Developer Token

I am following Apple's guide to musickit and I have been looking for a long time to resolve the following step:
Guide apple
I've already created the token.
Token
But I do not know what to do next where it says: "sign it with your MusicKit private key (see Create a MusicKit Private Key). Then encrypt the token using the Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. Specify the value ES256 in the algorithm header key (alg)".
I do not know how to encrypt ECDSA or where.
I do not know where to put the private keyword.
If you're still curious about this then pelauimagineering's example which worked perfectly for me.
If you don't already have:
Download pip, then two libraries: pyjwt & cryptography
On terminal do:
$ sudo easy_install pip
$ sudo pip install pyjwt
$ sudo pip install cryptography
Clone pelauimagineering's repository and edit the music_token.py
file replacing the secret variable with the .p8 key you downloaded.
Replace the keyId with the value you'll find at developer.apple.com
under certificates > keys, and then click the key of the app you
downloaded the .p8 file for and you'll see the key Id there.
Lastly, replace the teamId variable on the .py file with the 10 digit key found on your developer account at developer.apple.com/account and then click the membership tab and you'll see your 10 digit Id. Remember you need a developer token to do this which costs $99/year.
Here's the sample code to generate the token for NodeJS:
const fs = require('fs');
const jwt = require('jsonwebtoken');
const privateKey = fs.readFileSync('AuthKey_1234.p8').toString(); // file downloaded when you created your key
const jwtToken = jwt.sign({}, privateKey, {
algorithm: 'ES256',
expiresIn: '180d',
issuer: '1234V73RKG', // Your team ID
header: {
alg: 'ES256',
kid: '1234VPQXH4' // ID from the Key with MusicKit permissions
}
});
console.log("token:", jwtToken, "\n");
The JWT node module does all the hard work for you.
You can generate and sign your token from here. It is an apple developer token generator with an open source code, that can be found on github. Also you could find some documentation for it in this link.

Encryption with RSA public key on iOS

I write an iOS app to communicate with an existing server. The server generates RSA key pair(public key and private key), and sends public key to the client.
The client(the iOS app) have to encrypt with ONLY the public key, and sends the encrypted data to server.
So, I need a Objective-C function to do RSA encryption.
Input:
Plain text: hello world!
The public key:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+
zuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X
NSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT
qeox88Lc1ld7MsfggQIDAQAB
-----END PUBLIC KEY-----
Process:
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
Output:
uwGuSdCgDxAAN3M5THMrNcec3Fm/Kn+uUk7ty1s70oH0FNTAWz/7FMnEjWZYOtHe37G3D4DjqiWijyUCbRFaz43oVDUfkenj70NWm3tPZcpH8nsWYevc9a1M9GbnNF2jRlami8LLUTZiogypSVUuhcJvBZBOfea9cOonX6BG+vw=
Question:
How to implement this function?
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
I have had digg for a long time, on SO and google and Apple's document. I found out Apple need a .der file to do encryption, not only the public key.
I will answer my qustion:
1. create SecKeyRef with public key string
I am helped by this post: http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/#its-all-in-the-format
It led to my code: https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m#L34
2. use the SecKeyRef to encrypt input data
Use Apple's SecKeyEncrypt(https://developer.apple.com/library/ios/documentation/Security/Reference/certifkeytrustservices/index.html)
3. the full code on github
https://github.com/ideawu/Objective-C-RSA
If you are using your public and private keys then use SecKeyRef
to generate both keys else use keys provided by backend guys to communicate with server.
These are some third party sdks that can help for this purpose, i've used one of them that helped me a lot to encrypt and decrypt.
[1]: https://github.com/Kitura/Swift-JWT [2]: https://github.com/TakeScoop/SwiftyRSA [3]: https://github.com/soyersoyer/SwCrypt [4]: https://github.com/Kitura/BlueRSA
For further info visit below Apple link for official documentation
https://developer.apple.com/documentation/security

Is there any Elliptic Curve algorithm equivalent to RSA's asymmetric encryption?

I've been searching but I cant find anything about this... only EC Diffie-Hellman with symmetric cryptography, which is exactly what I do not want :(
Imagine this:
generate a random private key, k
then calculate a "public key" with ECC, d=kG
The algorithm I'm looking for is this: any message cyphered with the public key will "only" be decyphered by the owner of the private key.
Does this exists? Has anything like this been developed yet?
You could try ecc (pip install ecc)
from ecc.Key.Key import Key
# Create keypair
k=Key.generate(521)
# Encode public key
pub=k.encode()
# Encode private key
priv=k.encode(include_private=True)
# Decode public key
pubK=Key.decode(pub)
# Decode private key
privK=Key.decode(priv)
# Encrypt message
msg=pubK.encrypt("Test")
# Decrypt message
print privK.decrypt(msg)
Actually, El Gamal scheme, being based on Diffie–Hellman key exchange, presumes an asymmetric encryption algorithm, with private and public keys, so you should consider this. Computing the public key in this scheme will be as difficult as computing the discrete logarithm in the group.

Codesigning SWF?

AIR allows to inject code using Loader.LoadBytes()
this allows to download remote plugins as swf files which will have full access to everything that the AIR application has access to. This imposes a security risk, so it would be desirable to digitally sign the swf's.
What's the best way to do this and to verify the code signature?
I know the as3corelib has some encryption functionality and also for X.509 certificate - but I didn't find a ressource explaining how to use it. Also, maybe there's some 'official' way to codesign SWF's?
One robust method is using public key encryption, which goes something like this:
You will need an asymmetric encryption algorithm (eg, RSA), and a hash algorithm (eg, SHA, MD5).
Generate a public-private key pair.
Generate and checksum of the data using the hash algorithm.
Encrypt the checksum with the private key using the encryption algorithm. This becomes the "signature".
Send the data to the client along with the signature.
Decrypt the signature on the client with the public key to obtain the original checksum.
Generate a checksum from the data on the client.
Compare the checksums. If they match, then you know that the data came from you without alterations. If they do not match then you know the data was altered after it was sent from you, or it came from someone else.
See http://en.wikipedia.org/wiki/Public-key_cryptography
An attacker can bypass this security if they are able to intercept the connection and modify the original client SWF file and either change the public key, or remove the security mechanism entirely. Use TLS or SSL to prevent attackers intercepting the data.
An x.509 certificate is little more than a public key bundled with some meta-data. The standard also specifies a mechanism for validating the certificate, by relying on a certificate authority (CA) (see http://en.wikipedia.org/wiki/X.509).
The AS3Crypto library provides (amongst other things), an implementation of RSA, MD5, and an x.509 parser (see http://code.google.com/p/as3crypto/).
Here is some code. The signing process entails computing the hash of the data, then signing it with the private key to produce a signature, eg:
var rsa:RSAKey;
var md5:MD5;
var data:ByteArray = getSWFBytes();
var signature:ByteArray = new ByteArray();
var originalHash:ByteArray;
// read private key
rsa = PEM.readRSAPrivateKey(private_key);
// create the checksum of the original data
md5 = new MD5();
originalHash = md5.hash(original);
// encrypt the data using the private key
rsa.sign(data, signature, original.length);
The data and signature are sent to the client. The client decrypts the signature using the public key stored in the cert and compare it to the computed hash of the data, eg:
var rsa:RSAKey;
var md5:MD5;
var data:ByteArray = getSWFBytes();
var signature:ByteArray = new ByteArray();
var decryptedHash:ByteArray = new ByteArray();
var clientHash:ByteArray;
// load the certificate
var cert:X509Certificate = new X509Certificate(public_cert);
// get the public key from the cert
rsa = cert.getPublicKey();
// decrypt the signature with the public key
rsa.verify(signature, decryptedHash, encrypted.length);
// create a hash of the data
md5 = new MD5();
clientHash = md5.hash(data);
// compare the hashes
// isEqual compares the bytes in the input byte arrays, it returns true only of all bytes in both arrays match
if (isEqual(clientHash, decryptedHash))
trace("signature valid");
else
trace("signature invalid")
You can check if the certificate is signed like this:
var store:X509CertificateCollection = new MozillaRootCertificates();
var cert:X509Certificate = new X509Certificate(public_cert);
var isValid:Boolean = cert.isSigned(store, store);
You can load the raw SWF bytes like this:
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest(url_of_swf_to_load));
Example x.509 private key (usually created when you apply for a certificate):
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDoKlLzpJeLcoPYQQYPa0diM4zpZ+0rKeRxhx9ssq91DzwAeSmM
7wT03WLiLZkqPt2MS3uNo75zK5RtmjHqF6Ojfs2tbSdlCK5tpisvOAssuq0o5vIz
g/MhS2PIijnBtVB9XFSTXxhveKeIq1VgdB2wHW95+zhBF+Z1hsYcNRRFFwIDAQAB
AoGAI8wK2EhjmXvBuoFkJtJ6wjiCnKaKmiIueBbGkKMIjLsZnFUSRAnCsOLF0WwI
dswUqwIkfdVmkymADFo/IgIdF9hLGNLRskIPKGZWEUC8d5ZJnRg+nuzi2c2msN5u
/BvCCgL5/shBhO5KvrPbU/Fbs/k4saCDQZ2EO4HpueRZWGkCQQD6hC0pTfyW4yQT
Qr/dY7FhOwdOh/8ewGyXBa9ruOuZqTR23Ya20O8NuF22+NqW9AZl7uioiTZyZkOV
jqAckelrAkEA7T9QVdK+QcaQSznrZPJpXlSIDLSBRWjaPKBoypnNTF3y3JkUQE0L
iA0c2oUc8D+LCgx9vA0Ai0IzwzrIec+iBQJAJb5YV4rKbalXPBeodKCajv2nwis3
QtjXA4H1xhMcXBBkOSxzKYQdIEIQzIp91JR7ikwOfaX+sAm8UQImGWfadQJAMAb4
KVePQluDDGd+OqJEKF9uZzwHS1jNjSZf8FuwTrxaFMQ8cEPoiLM22xnFYPFMIU2k
CnSLXqWZOvVkbhxVTQJAL3xIc5AUbhsEp7ZeeJrkPRv5rCObmLw0+wIaERtMX83b
PNM0TpzY6EXk+geTCqudAipYF/A7qn38wpOh+PuuVg==
-----END RSA PRIVATE KEY-----
Example cert:
-----BEGIN CERTIFICATE-----
MIID4zCCA0ygAwIBAgIJAL7k5X3sCvniMA0GCSqGSIb3DQEBBQUAMIGoMQswCQYD
VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTERMA8GA1UEBxMIU2FuIEpvc2Ux
FDASBgNVBAoTC2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