SignatureLoader.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #if !UNITY_WSA || UNITY_EDITOR
  2. using System.Security.Cryptography;
  3. #else
  4. using Windows.Security.Cryptography;
  5. using Windows.Security.Cryptography.Core;
  6. #endif
  7. using System;
  8. namespace XLua
  9. {
  10. public class SignatureLoader
  11. {
  12. private LuaEnv.CustomLoader userLoader;
  13. #if !UNITY_WSA || UNITY_EDITOR
  14. RSACryptoServiceProvider rsa;
  15. SHA1 sha;
  16. #else
  17. AsymmetricKeyAlgorithmProvider rsa;
  18. CryptographicKey key;
  19. #endif
  20. public SignatureLoader(string publicKey, LuaEnv.CustomLoader loader)
  21. {
  22. #if !UNITY_WSA || UNITY_EDITOR
  23. rsa = new RSACryptoServiceProvider();
  24. rsa.ImportCspBlob(Convert.FromBase64String(publicKey));
  25. sha = new SHA1CryptoServiceProvider();
  26. #else
  27. rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
  28. key = rsa.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
  29. #endif
  30. userLoader = loader;
  31. }
  32. byte[] load_and_verify(ref string filepath)
  33. {
  34. byte[] data = userLoader(ref filepath);
  35. if (data == null)
  36. {
  37. return null;
  38. }
  39. if (data.Length < 128)
  40. {
  41. throw new InvalidProgramException(filepath + " length less than 128!");
  42. }
  43. byte[] sig = new byte[128];
  44. byte[] filecontent = new byte[data.Length - 128];
  45. Array.Copy(data, sig, 128);
  46. Array.Copy(data, 128, filecontent, 0, filecontent.Length);
  47. #if !UNITY_WSA || UNITY_EDITOR
  48. if (!rsa.VerifyData(filecontent, sha, sig))
  49. {
  50. throw new InvalidProgramException(filepath + " has invalid signature!");
  51. }
  52. #else
  53. if (!CryptographicEngine.VerifySignature(key, CryptographicBuffer.CreateFromByteArray(filecontent), CryptographicBuffer.CreateFromByteArray(sig)))
  54. {
  55. throw new InvalidProgramException(filepath + " has invalid signature!");
  56. }
  57. #endif
  58. return filecontent;
  59. }
  60. public static implicit operator LuaEnv.CustomLoader(SignatureLoader signatureLoader)
  61. {
  62. return signatureLoader.load_and_verify;
  63. }
  64. }
  65. }