How can I do public key pinning in Flutter?

有些话、适合烂在心里 提交于 2019-11-30 09:08:17

问题


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?


回答1:


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);



回答2:


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?



来源:https://stackoverflow.com/questions/54726406/how-can-i-do-public-key-pinning-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!