安全開發 Windows app 的簡介Intro to secure Windows app development

這篇簡介文章將協助應用程式設計人員和開發人員,能更了解各種能快速建立安全的通用 Windows 平台 (UWP) 應用程式的 Windows 10 平台功能。This introductory article helps app architects and developers better understand the various Windows 10 platform capabilities that accelerate creating secure Universal Windows Platform (UWP) apps. 文章會詳細說明如何在每個階段 (驗證、傳輸中資料及靜態資料) 中使用可用的 Windows 安全性功能。It details how to use the Windows security features available at each of the following stages: authentication, data-in-flight, and data-at-rest. 如需深入了解每個主題,請檢視包含在每個章節中的額外資源。You can find more in-depth information on each topic by reviewing the additional resources included in each chapter.

1 簡介1 Introduction

開發安全的應用程式是種挑戰。Developing a secure app can be a challenge. 今日的世界充滿各種行動、社交、雲端,及複雜的企業應用程式,而且瞬息萬變,使得客戶期待應用程式會有更快的上市及更新速度。In today’s fast-paced world of mobile, social, cloud, and complex enterprise apps, customers expect apps to become available and updated faster than ever. 而客戶也會使用許多不同類型的裝置,更增添了應用程式開發的複雜性。They also use many types of devices, further adding to the complexity of creating app experiences. 如果您要建置適用於 Windows 10 通用 Windows 平台 (UWP) 的應用程式,這些裝置可能包含傳統的桌上型電腦、筆記型電腦、平板電腦及行動裝置,再加上種類日益增加的新裝置,包括物聯網、Xbox One、Microsoft Surface Hub 及 HoloLens。If you build for the Windows 10 Universal Windows Platform (UWP), that could include the traditional list of desktops, laptops, tablets, and mobile devices; in addition to a growing list of new devices spanning the Internet of Things, Xbox One, Microsoft Surface Hub, and HoloLens. 身為開發人員,您必須確保自己的應用程式能在所有平台或相關裝置之間安全地傳輸及儲存資料。As the developer, you must ensure your apps communicate and store data securely, across all the platforms or devices involved.

以下是幾個利用 Windows 10 安全性功能的好處。Here are some of the benefits of utilizing Windows 10 security features.

  • 您在所有支援 Windows 10 的裝置上將擁有標準化的安全性,方法是使用一致的安全性元件和技術 API。You will have standardized security across all devices that support Windows 10, by using consistent APIs for security components and technologies.
  • 如果您之前使用自訂的程式碼來處理這些安全性案例,現在您需要編寫、測試及維護的程式碼將會減少。You write, test, and maintain less code than you would if you implemented custom code to cover these security scenarios.
  • 您的應用程式會更加穩定、安全,原因是您將使用作業系統來控制應用程式存取自己的資源,以及本機或遠端系統資源的方式。Your apps become more stable and secure because you use the operating system to control how the app accesses its resources and local or remote system resources.

在驗證期間,系統會驗證要求存取特定服務的使用者身分識別。During authentication, the identity of a user requesting access to a particular service is validated. Windows Hello 是 Windows 10 的元件,可協助您在 Windows 應用程式中建立更安全的驗證機制。Windows Hello is the component in Windows 10 that helps create a more secure authentication mechanism in Windows apps. 您可以藉由這個元件來使用個人識別碼 (PIN) 或生物特徵辨識技術 (例如使用者的指紋、臉部或虹膜),以便為您的應用程式實行多重要素驗證。With it, you can use a Personal Identification Number (PIN) or biometrics such as the user’s fingerprints, face, or iris to implement multi-factor authentication for your apps.

傳輸中資料就是指連線,以及透過該連線傳輸的訊息。Data-in-flight refers to the connection and the messages transferred across it. 舉例來說,當您使用 Web 服務來擷取遠端伺服器上的資料時,An example of this is retrieving data from a remote server using web services. 使用安全通訊端層 (SSL) 和安全超文字傳輸通訊協定 (HTTPS) 可確保連線的安全。The use of Secure Sockets Layer (SSL) and Secure Hypertext Transfer Protocol (HTTPS) ensures the security of the connection. 避免第三方存取這些訊息,或是避免未經授權的應用程式使用 Web 服務進行通訊,是保護傳輸中資料的重要關鍵。Preventing intermediary parties from accessing these messages, or unauthorized apps from communicating with the web services, is key to securing data in flight.

最後,靜態資料與存放在記憶體中或儲存媒體上的資料有關。Lastly, data-at-rest relates to data residing in memory or on storage media. Windows 10 有種應用程式模型,能防止應用程式之間未經授權的資料存取,以及提供加密 API 來進一步保護裝置上的資料。Windows 10 has an app model that prevents unauthorized data access between apps, and offers encryption APIs to further secure data on the device. 而稱為「認證保險箱」的功能在搭配可防止應用程式存取裝置上資訊的作業系統之後,就能用來將使用者認證安全地儲存在裝置上。A feature called Credential Locker can be used to securely store user credentials on the device, with the operating system preventing other apps from accessing them.

2 驗證因素2 Authentication Factors

為了要保護資料,要求存取資料的使用者必須要經過身分識別,並獲得授權來存取該使用者要求的資料。To protect data, the person requesting access to it must be identified and authorized to access the data resources they request. 識別使用者身分的程序稱為「驗證」,而決定給予某資源存取權限的過程則叫「授權」。The process of identifying a user is called authentication, and determining access privileges to a resource is called authorization. 這兩者是關係密切的作業,且對於使用者來說可能難以分辨。These are closely related operations, and to the user they might be indistinguishable. 它們可以是相當簡單或複雜的作業,完全取決於許多因素:例如,資料是存放在單一伺服器上,還是分散到許多系統中。They can be relatively simple or complex operations, depending on many factors: for example, whether the data resides on one server or is distributed across many systems. 提供驗證及授權服務的伺服器稱為「識別提供者」。The server providing the authentication and authorization services is referred to as the identity provider.

使用者為了要向特定的服務和/或應用程式驗證自己的身分,會使用由您知道的事情、您擁有的東西,及/或您扮演的角色來組成的認證。To authenticate themselves with a particular service and/or app, the user employs credentials made up of something they know, something they have, and/or something they are. 而這些資訊每個都叫做驗證因素。Each of these are called authentication factors.

  • 使用者知道的資訊通常是密碼,但也可以是個人識別碼 (PIN) 或「祕密」的問題與答案組。Something the user knows is usually a password, but it can also be a personal identification number (PIN) or a “secret” question-and-answer pair.
  • 使用者擁有的物品大多數是硬體記憶體裝置,例如內含使用者專屬驗證資料的 USB 隨身碟。Something the user has is most often a hardware memory device such as a USB stick containing the authentication data unique to the user.
  • 使用者本身的特質通常包含使用者的指紋,但有些因素越來越受歡迎,例如使用者的語音、臉部、眼睛特徵,或是行為模式。Something the user is often encompasses their fingerprints, but there are increasingly popular factors like the user’s speech, facial, ocular (eye) characteristics, or patterns of behavior. 當這些因素的度量儲存成資料之後,就稱為生物特徵辨識技術。When stored as data, these measurements are called biometrics.

使用者建立的密碼本身就是驗證因素,但這通常不夠,因為任何知道密碼的人,都能冒充擁有該密碼的使用者。A password created by the user is an authentication factor in itself, but it often isn’t sufficient; anyone who knows the password can impersonate the user who owns it. 智慧卡能提供更高層級的安全性,但是它可能會遭竊、遺失,或放錯地方。A smart card can provide a higher level of security, but it might be stolen, lost, or misplaced. 能利用指紋或眼部掃描來驗證使用者身分的系統,或許可提供最高層級和最便利的安全性,但這需要昂貴和專用的硬體 (例如,臉部辨識用的 Intel RealSense 攝影機),並非所有使用者都能負擔。A system that can authenticate a user by their fingerprint or by an ocular scan might provide the highest and most convenient level of security, but it requires expensive and specialized hardware (for example, an Intel RealSense camera for facial recognition) that might not be available to all users.

設計系統所使用的驗證方法,對於資料安全性來說是個複雜且重要的部分。Designing the method of authentication used by a system is a complex and important aspect of data security. 一般而言,您使用於驗證的因素越多,系統就越安全。In general, the greater number of factors you use in authentication, the more secure the system is. 然而,驗證必須是便於使用的。At the same time, authentication must be usable. 使用者通常會一天登入系統許多次,因此驗證程序必須快速。A user will usually log in many times a day, so the process must be fast. 您選擇的驗證類型是安全性和易於使用性之間的取捨;單一因素驗證最不安全但最易於使用,而多重要素驗證會隨因素的增加而更加安全,但也更加複雜。Your choice of authentication type is a trade-off between security and ease of use; single-factor authentication is the least secure and easiest to use, and multi-factor authentication becomes more secure, but more complex as more factors are added.

2.1 單一因素驗證2.1 Single-factor authentication

這種形式的驗證是根據單一使用者認證來進行的。This form of authentication is based on a single user credential. 這認證通常是密碼,但也可能是個人識別碼 (PIN)。This is usually a password, but it could also be a personal identification number (PIN).

以下是單一因素驗證的程序。Here’s the process of single-factor authentication.

  • 使用者將自己的使用者名稱和密碼提供給識別提供者。The user provides their username and password to the identity provider. 識別提供者就是驗證使用者的身分識別的伺服器程序。The identity provider is the server process that verifies the identity of the user.
  • 識別提供者會檢查該使用者名稱及密碼,是否與儲存在系統中的使用者名稱及密碼相同。The identity provider checks whether the username and password are the same as those stored in the system. 在大多數的情況下,密碼會經過加密來提供額外的安全性,讓他人無法讀取。In most cases, the password will be encrypted, providing additional security so that others cannot read it.
  • 識別提供者會傳回指出驗證是否成功的驗證狀態。The identity provider returns an authentication status that indicates whether the authentication was successful.
  • 如果成功,就會開始資料交換。If successful, data exchange begins. 如果不成功,使用者就必須重新驗證身分。If unsuccessful, the user must be re-authenticated.

單一因素驗證

這種驗證方法是目前各種服務最常使用的。Today, this method of authentication is the most commonly used one across services. 但在只用這種方法來驗證時,它也是最不安全的驗證形式。It is also the least secure form of authentication when used as the only means of authentication. 密碼的複雜性需求、「秘密問題」,以及定期的密碼變更都能讓密碼更安全,但這會讓使用者承受比較大的負擔,且使用者並非能有效對抗駭客的對象。Password complexity requirements, "secret questions," and regular password changes can make using passwords more secure, but they put more burden on users and they’re not an effective deterrent against hackers.

使用密碼的挑戰在於,成功猜出密碼,比入侵擁有不只一個因素的系統還要容易。The challenge with passwords is that it is easier to guess them successfully than systems that have more than one factor. 如果駭客向某家網路小店購買內含使用者帳戶及雜湊密碼的資料庫,他們就能在其他網站上使用這些密碼。If they steal a database with user accounts and hashed password from a little web shop, they can use the passwords used on other web sites. 使用者通常會一直重複使用相同的帳戶,因為複雜的密碼是很難記住的。Users tend to reuse accounts all the time, because complex passwords are hard to remember. 對於 IT 部門來說,管理密碼也有其複雜性,像是必須提供密碼重設機制、需要經常更新密碼,以及必須將密碼儲存在安全的方法。For an IT department, managing passwords also brings with it the complexity of having to offer reset mechanisms, requiring frequent updates to passwords, and storing them in a safe manner.

儘管單一因素驗證有許多缺點,但它給予使用者認證的控制權。For all of its disadvantages, single-factor authentication gives the user control of the credential. 使用者可以建立及修改密碼,而且只要鍵盤就能進行驗證程序。They create it and modify it, and only a keyboard is needed for the authentication process. 這是單一因素驗證和多重要素驗證的主要差異。This is the main aspect that distinguishes single-factor from multi-factor authentication.

2.1.1 Web 驗證代理人2.1.1 Web authentication broker

如同先前所討論的,對於 IT 部門來說,使用密碼驗證的挑戰之一,在於管理使用者名稱/密碼資料庫、重設機制等等的經常費用提高了。目前有種越來越受歡迎的選擇,就是仰賴第三方識別提供者來提供藉由 OAuth (開放的驗證標準) 驗證的程序。As previously discussed, one of the challenges with password authentication for an IT department is the added overhead of managing the base of usernames/passwords, reset mechanisms, etc. An increasingly popular option is to rely on third-party identity providers that offer authentication through OAuth, an open standard for authentication.

IT 部門只要使用 OAuth,就能有效地把維護使用者名稱及密碼資料庫、密碼重設功能等複雜工作「外包」給第三方識別提供者,例如 Facebook、Twitter 或 Microsoft。Using OAuth, IT departments can effectively "outsource" the complexity of maintaining a database with usernames and passwords, reset password functionality, etc. to a third party identity provider like Facebook, Twitter or Microsoft.

使用者在這些平台上可以完全掌控自己的身分識別,但在使用者經過驗證,且在該使用者的同意下,應用程式可要求識別提供者提供權杖,用來授權給已經過驗證的使用者。Users have complete control over their identity on these platforms, but apps can request a token from the provider, after the user is authenticated and with their consent, which can be used to authorize authenticated users.

Windows 10 的 Web 驗證代理人提供一組 API 和基礎結構,讓應用程式來使用驗證及授權通訊協定 (例如 OAuth 和 OpenID)。The web authentication broker in Windows 10 provides a set of APIs and infrastructure for apps to use authentication and authorization protocols like OAuth and OpenID. 應用程式可透過 WebAuthenticationBroker API 來啟動驗證作業,以傳回 WebAuthenticationResultApps can initiate authentication operations through the WebAuthenticationBroker API, resulting in the return of a WebAuthenticationResult. 下圖為通訊流程的概觀。An overview of the communication flow is illustrated in the following figure.

WAB 工作流程

app 會擔任代理人,透過 app 中的 WebView 向識別提供者啟動驗證作業。The app acts as the broker, initiating the authentication with the identity provider through a WebView in the app. 識別提供者在驗證使用者的身分之後,會將權杖傳回給應用程式,讓應用程式能用來向識別提供者要求該使用者的相關資訊。When the identity provider has authenticated the user, it returns a token to the app that can be used to request information about the user from the identity provider. 基於安全性考量,應用程式必須先向識別提供者註冊,才可以向識別提供者進行代理驗證程序。As a security measure, the app must be registered with the identity provider before it can broker the authentication processes with the identity provider. 每個識別提供者的註冊步驟都不相同。This registration steps differ for each provider.

以下是呼叫 WebAuthenticationBroker API 來與識別提供者進行通訊的一般工作流程。Here’s the general workflow for calling the WebAuthenticationBroker API to communicate with the provider.

  • 建立要傳送給識別提供者的要求字串。Construct the request strings to be sent to the identity provider. 每個 Web 服務的字串數目和每個字串中的資訊都不相同,但它通常包含 2 個 URI 字串,且每個字串都有 1 個 URL:一個是驗證要求的傳送目的地,另一個是授權完成之後使用者將被重新導向的目的地。The number of strings, and the information in each string, is different for each web service but it usually includes two URI strings each containing a URL: one to which the authentication request is sent, and one to which the user is redirected after authorization is complete.
  • 呼叫會利用要求字串傳遞的 WebAuthenticationBroker.AuthenticateAsync,並等待識別提供者的回應。Call WebAuthenticationBroker.AuthenticateAsync, passing in the request strings, and wait for the response from the identity provider.
  • 收到回應時,呼叫 WebAuthenticationResult.ResponseStatus 以取得狀態。Call WebAuthenticationResult.ResponseStatus to get the status when the response is received.
  • 如果通訊成功,則處理識別提供者傳回的回應字串。If the communication is successful, process the response string returned by the identity provider. 如果失敗,則處理錯誤。If unsuccessful, process the error.

如果通訊成功,則處理識別提供者傳回的回應字串。If the communication is successful, process the response string returned by the identity provider. 如果失敗,則處理錯誤。If unsuccessful, process the error.

下列為這個處理程序的 C# 程式碼範例。Sample C# code that for this process is below. 如需資訊和詳細的逐步解說,請參閱 WebAuthenticationBrokerFor information and a detailed walkthrough, see WebAuthenticationBroker. 如需完整的程式碼範例,請查看 GitHub 上的 WebAuthenticationBroker 範例For a complete code sample, check out the WebAuthenticationBroker sample on GitHub.

string startURL = "https://<providerendpoint>?client_id=<clientid>";
string endURL = "http://<AppEndPoint>";

var startURI = new System.Uri(startURL);
var endURI = new System.Uri(endURL);

try
{
    WebAuthenticationResult webAuthenticationResult = 
        await WebAuthenticationBroker.AuthenticateAsync( 
            WebAuthenticationOptions.None, startURI, endURI);

    switch (webAuthenticationResult.ResponseStatus)
    {
        case WebAuthenticationStatus.Success:
            // Successful authentication. 
            break;
        case WebAuthenticationStatus.ErrorHttp:
            // HTTP error. 
            break;
        default:
            // Other error.
        break;
    }
}
catch (Exception ex)
{
    // Authentication failed. Handle parameter, SSL/TLS, and
    // Network Unavailable errors here. 
}

2.2 多重要素驗證2.2 Multi-factor authentication

多重要素驗證使用一個以上的驗證因素,Multi-factor authentication makes use of more than one authentication factor. 通常是「您知道的事情」(例如密碼) 與「您擁有的東西」(例如行動電話或智慧卡) 的組合。Usually, "something you know," such as a password, is combined with "something you have," which can be a mobile phone or a smart card. 就算攻擊者發現使用者的密碼,在沒有裝置或智慧卡的情況下,攻擊者仍然無法存取帳戶。Even if an attacker discovers the user’s password, the account is still inaccessible without the device or card. 而且如果攻擊者取得裝置或智慧卡,在沒有密碼的情況下,該裝置或智慧卡也沒有任何用處。And if only the device or card is compromised, it is not useful to the attacker without the password. 因此,多重要素驗證比單一因素驗證更加安全,但也更加複雜。Multi-factor authentication is therefore more secure, but also more complex, than single-factor authentication.

使用多重要素驗證的服務,通常會讓使用者選擇如何讓服務接收第二個認證。Services that use multi-factor authentication will often give the user a choice in how they receive the second credential. 舉例來說,使用這種驗證類型的服務,通常會利用簡訊把驗證碼傳送到使用者的行動電話中。An example of this type of authentication is a commonly used process where a verification code is sent to the user’s mobile phone using SMS.

  • 使用者將自己的使用者名稱和密碼提供給識別提供者。The user provides their username and password to the identity provider.
  • 識別提供者會驗證使用者名稱和密碼 (就跟單一因素驗證的程序一樣),然後尋找儲存在系統中的使用者行動電話號碼。The identity provider verifies the username and password as in single-factor authorization, and then looks up the user’s mobile phone number stored in the system.
  • 伺服器會將內含系統所產生驗證碼的簡訊傳送到使用者的行動電話。The server sends an SMS message containing a generated verification code to the user’s mobile phone.
  • 使用者透過系統提供給使用者的表單,將驗證碼提供給識別提供者。The user provides the verification code to the identity provider; through a form presented to the user.
  • 伺服器會傳回驗證狀態,指出這兩種認證是否都已驗證成功。The identity provider returns an authentication status that indicates whether the authentication of both credentials were successful.
  • 如果成功,就會開始資料交換。If successful, data exchange begins. 如果不成功,使用者就必須重新驗證。Otherwise, the user must be re-authenticated.

雙因素驗證

如您所見,這個程序也與單一因素驗證不同,因為第二個使用者認證是傳送給使用者,而不是由使用者建立或提供。As you can see, this process also differs from single-factor authentication in that the second user credential is sent to the user instead of being created or provided by the user. 因此使用者對於必要的認證並沒有完全的控制權。The user is therefore not in complete control of the necessary credentials. 把智慧卡當做第二個認證時亦是如此:是由組織負責製作智慧卡,然後提供給使用者。This also applies when a smart card is used as the second credential: the organization is in charge of creating and providing it to the user.

2.2.1 Azure Active Directory2.2.1 Azure Active Directory

Azure Active Directory (Azure AD) 是雲端式身分識別及存取管理服務,可做為單一因素驗證或多重要素驗證的識別提供者。Azure Active Directory (Azure AD) is a cloud-based identity and access management service that can serve as the identity provider in single-factor or multi-factor authentication. Azure AD 驗證可以單獨使用,或是搭配驗證碼來使用。Azure AD authentication can be used with or without a verification code.

雖然 Azure AD 也可以實行單一因素驗證,但企業通常需要安全性更高的多重要素驗證。While Azure AD can also implement single-factor authentication, enterprises usually require the higher security of multi-factor authentication. 在多重要素驗證的設定中,利用 Azure AD 帳戶來驗證的使用者,可以選擇把驗證碼當做簡訊傳送到自己的行動電話,或是傳送到 Azure Authenticator 行動應用程式。In a multi-factor authentication configuration, a user authenticating with an Azure AD account has the option of having a verification code sent as an SMS message either to their mobile phone or the Azure Authenticator mobile app.

此外,Azure AD 可以做為 OAuth 提供者,為標準使用者提供跨多重平台之應用程式的驗證及授權機制。Additionally, Azure AD can be used as an OAuth provider, providing the standard user with an authentication and authorization mechanism to apps across various platforms. 如需深入了解,請參閱 Azure Active Directory在 Azure 的多重要素驗證To learn more, see Azure Active Directory and Multi-Factor Authentication on Azure.

2.4 Windows Hello2.4 Windows Hello

在 Windows 10 中,方便的多重要素驗證機制已經內建在作業系統中。In Windows 10, a convenient multi-factor authentication mechanism is built into the operating system. Windows Hello 就是 Windows 10 內建的新生物特徵辨識登入系統。Windows Hello is the new biometric sign-in system built into Windows 10. 因為此功能是直接內建於作業系統,所以 Windows Hello 讓使用者能夠使用臉部或指紋辨識來解除鎖定使用者的裝置。Because it is built directly into the operating system, Windows Hello allows face or fingerprint identification to unlock users’ devices. Windows 安全的認證存放區會保護裝置上的生物特徵辨識資料。The Windows secure credential store protects biometric data on the device.

Windows Hello 可為裝置提供健全的方式來辨識個別使用者,這也就是使用者與所要求服務或資料項目之間路徑的第一個部分。Windows Hello provides a robust way for a device to recognize an individual user, which addresses the first part of the path between a user and a requested service or data item. 裝置在成功辨識使用者之後,仍然需要驗證使用者的身分,才能決定是否要授與所要求資源的存取權。After the device has recognized the user, it still must authenticate the user before determining whether to grant access to a requested resource. Windows Hello 也會提供與 Windows 完全整合的增強式雙因素驗證 (2FA),利用特定裝置和生物特徵辨識技術或 PIN 的組合,來取代可重複使用的密碼。Windows Hello also provides strong two-factor authentication (2FA) that is fully integrated into Windows and replaces reusable passwords with the combination of a specific device, and a biometric gesture or PIN. PIN 是使用者在註冊 Microsoft 帳戶時所指定的。The PIN is specified by the user as part of their Microsoft account enrollment.

不過,Windows Hello 不只是用來取代傳統的 2FA 系統。Windows Hello isn’t just a replacement for traditional 2FA systems, though. 這在概念上類似智慧卡:驗證是使用密碼編譯基本類型而不是字串比較來執行,而使用者的金鑰內容在防竄改的硬體內部是安全的。It’s conceptually similar to smart cards: authentication is performed by using cryptographic primitives instead of string comparisons, and the user’s key material is secure inside tamper-resistant hardware. Microsoft Hello 也不需要智慧卡部署所需的額外基礎結構元件。Microsoft Hello doesn't require the extra infrastructure components required for smart card deployment, either. 特別的是,您並不需要公開金鑰基礎結構 (PKI) 來管理憑證 (如果您目前沒有 PKI)。In particular, you don’t need a Public Key Infrastructure (PKI) to manage certificates, if you don’t currently have one. Windows Hello 結合智慧卡的主要優點,有虛擬智慧卡的部署彈性及實體智慧卡的強大安全性,卻沒有兩者的任何缺點。Windows Hello combines the major advantages of smart cards—deployment flexibility for virtual smart cards and robust security for physical smart cards—without any of their drawbacks.

使用者必須先讓裝置向 Windows Hello 註冊,才能使用該裝置進行驗證。A device must be registered with Windows Hello before users can authenticate with it. Windows Hello 會使用非對稱式 (公開/私密金鑰) 加密,讓其中一方使用公開金鑰來為資料加密,而另一方使用私密金鑰來解密。Windows Hello uses asymmetric (public/private key) encryption in which one party uses a public key to encrypt the data that the other party can decrypt using a private key. 就 Windows Hello 來說,它會建立公開/私密金鑰組,並將私密金鑰寫入裝置的信賴平台模組 (TPM) 晶片中。In the case of Windows Hello, it creates a set of public/private key pairs and writes the private keys to the device’s Trusted Platform Module (TPM) chip. 裝置註冊之後,UWP app 就能呼叫系統 API 來擷取使用者的公開金鑰,讓系統能用來讓使用者在伺服器上註冊。After a device has been registered, UWP apps can call system APIs to retrieve the user’s public key, which can be used to register the user on the server.

應用程式的註冊工作流程可能如下:The registration workflow of an app might look like the following:

Windows Hello 註冊

您所收集註冊資訊中的身分辨識資訊,可能比這簡單案例中所收集的多出許多。The registration information you collect may include a lot more identifying information than it does in this simple scenario. 舉例來說,如果您的應用程式存取某個受保護的服務 (例如銀行服務),您必須要求身分識別證明及其他項目,做為註冊程序的一部分。For example, if your app accesses a secured service such as one for banking, you’d need to request proof of identity and other things as part of the sign-up process. 當所有條件都符合之後,這位使用者的公開金鑰將會儲存在後端,讓該使用者下次使用服務時可用來進行驗證。Once all the conditions are met, the public key of this user will be stored in the back-end and used to validate the next time the user uses the service.

如需 Windows Hello 的詳細資訊,請參閱 Windows Hello 指南Windows Hello 開發人員指南For more information on Windows Hello, see the Windows Hello guide and the Windows Hello developer guide.

3 傳輸中資料的安全性方法3 Data-in-flight security methods

傳輸中資料的安全性方法,適用於連線到網路的裝置之間傳輸的資料。Data-in-flight security methods apply to data in transit between devices connected to a network. 資料可能是在私人公司內部網路的高安全性環境中的不同系統之間傳輸,或是在網路上的非安全環境中的用戶端和 Web 服務之間傳輸。The data may be transferred between systems on the high-security environment of a private corporate intranet, or between a client and web service in the non-secure environment of the web. Windows 10 應用程式透過自己的網路 API 支援 SSL 等標準,並搭配 Azure API Management 等技術來運作,讓開發人員可確保自己的應用程式有適當的安全性層級。Windows 10 apps support standards such as SSL through their networking APIs, and work with technologies such as Azure API Management with which developers can ensure the appropriate level of security for their apps.

3.1 遠端系統驗證3.1 Remote system authentication

一般而言,會與遠端電腦系統進行通訊的案例有兩種。There are two general scenarios where communication occurs with a remote computer system.

  • 本機伺服器透過直接連線來驗證使用者。A local server authenticates a user over a direct connection. 例如,當伺服器和使用者都在公司的內部網路中時。For example, when the server and the client are on a corporate intranet.
  • Web 服務透過網際網路進行通訊。A web service is communicated with over the Internet.

Web 服務通訊的安全性需求,會比在直接連線案例中的需求還要高,因為資料不再是安全網路的一部分,且惡意攻擊者想要攔截資料的可能性也比較高。Security requirements for web service communication are higher than those in direct connection scenarios, as data is no longer only a part of a secure network and the likelihood of malicious attackers looking to intercept data is also higher. 由於會有各種類型的裝置存取服務,這些服務可能會建置為 RESTful 服務 (而非 WCF 等服務),這代表服務的驗證與授權也有了新的挑戰。Because various types of devices will access the service, they will likely be built as RESTful services, as opposed to WCF, for instance, which means authentication and authorization to the service also introduces new challenges. 我們將討論兩種安全的遠端系統通訊的需求。We’ll discuss two requirements for secure remote system communication.

第一種需求是訊息機密性:用戶端與 Web 服務之間傳遞的資訊 (例如使用者的身分識別及其他個人資訊),在傳輸過程中不得被第三方讀取。The first requirement is message confidentiality: The information passed between the client and the web services (for example, the identity of the user and other personal information) must not be readable by third parties while in transit. 這通常是透過為傳送訊息所用的連線加密,以及為訊息本身加密來達成。This is usually accomplished by encrypting the connection over which messages are sent and by encrypting the message itself. 在私密/公開金鑰加密方面,公開金鑰是所有人都能使用的,且會用來為要傳送給特定收件者的訊息加密。In private/public key encryption, the public key is available to anyone, and is used to encrypt messages to be sent to a specific receiver. 而私密金鑰是只有收件者才能擁有的,且會用來為訊息解密。The private key is only held by the receiver and is used to decrypt the message.

第二種需求是訊息完整性:用戶端與 Web 服務必須能確認自己收到的訊息是由另一方有意傳送的,且訊息在傳輸過程中沒有遭到竄改。The second requirement is message integrity: The client and the web service must be able to verify that the messages they receive are the ones intended to be sent by the other party, and that the message has not been altered in transit. 這可透過以數位簽章簽署訊息,以及使用憑證驗證來達成。This is accomplished by signing messages with digital signatures and using certificate authentication.

3.2 SSL 連線3.2 SSL connections

Web 服務為了要建立及維護與用戶端之間的安全連線,可以使用安全超文字傳輸通訊協定 (HTTPS) 所支援的安全通訊端層 (SSL)。To establish and maintain secure connections to clients, web services can use Secure Sockets Layer (SSL), which is supported by the Secure Hypertext Transfer Protocol (HTTPS). SSL 藉由支援公開金鑰加密和伺服器憑證,來提供訊息機密性和完整性。SSL provides message confidentiality and integrity by supporting public key encryption as well as server certificates. 傳輸層安全性 (TLS) 已取代 SSL,但 TLS 通常還是會被稱為 SSL。SSL is superseded by Transport Layer Security (TLS), but TLS is often casually referred to as SSL.

當用戶端要求存取伺服器上的資源時,SSL 會啟動與伺服器之間的交涉程序,When a client requests access to a resource on a server, SSL starts a negotiation process with the server. 這就稱為 SSL 信號交換。This is called an SSL handshake. 而加密層級、公開和私密金鑰組,以及用戶端與伺服器憑證中的身分識別資訊,是雙方同意在 SSL 連線期間所有通訊的基礎。An encryption level, a set of public and private encryption keys, and the identity information in the client and server certificates are agreed upon as the basis of all communication for the duration of the SSL connection. 伺服器也可能會在這個階段要求用戶端進行驗證。The server may also require the client to be authenticated at this time. 連線建立之後,所有訊息都會使用交涉的公開金鑰加密,直到連線關閉為止。Once the connection is established, all messages are encrypted with the negotiated public key until the connection closes.

3.2.1 SSL 關聯3.2.1 SSL pinning

雖然 SSL 可使用加密和憑證來提供訊息機密性,卻完全不會檢查正在與用戶端進行通訊的伺服器,是否為正確的伺服器。While SSL can provide message confidentiality using encryption and certificates, it does nothing to verify that the server with which the client is communicating is the correct one. 未經授權的第三方可能會模仿伺服器的行為,進而攔截用戶端所傳輸的機密資料。The server’s behavior can be mimicked by an unauthorized third-party, intercepting the sensitive data that the client transmits. 為避免發生這種情況,用戶端會使用稱為 SSL 關聯的技術,來確認伺服器上的憑證是否為用戶端預期和信任的憑證。To prevent this, a technique called SSL pinning is used to verify that the certificate on the server is the certificate that the client expects and trusts.

在應用程式中使用 SSL 關聯的方式有幾種,但每種都各有利弊。There are a few different ways to implement SSL pinning in apps, each with their own pros and cons. 最簡單的方式,就是透過應用程式套件資訊清單中的憑證宣告。The easiest approach is via the Certificates declaration in the app’s package manifest. 這個宣告可讓應用程式套件安裝數位憑證,並指定對這些憑證的專有信任。This declaration enables the app package to install digital certificates and specify exclusive trust in them. 這會讓應用程式只會與憑證鏈結中有對應憑證的伺服器建立 SSL 連線。This results in SSL connections being allowed only between the app and servers that have the corresponding certificates in their certificate chain. 這種機制也啟用安全的自我簽署憑證,因為並不需要依靠第三方來擔任受信任的公開憑證授權單位。This mechanism also enables the secure use of self-signed certificates, as no third party dependency is needed on trusted public certification authorities.

SSL 資訊清單

如需提高對驗證邏輯的控制,您可以使用 API 來驗證伺服器為回應 HTTPS 要求所傳回的憑證。For more control over the validation logic, APIs are available to validate the certificate(s) returned by the server in response to an HTTPS request. 請注意,這個方法需要傳送要求及檢查回應,因此請務必在實際傳送要求中的機密資訊之前,先新增這個驗證方法。Note that this method requires sending a request and inspecting the response, so be sure to add this as a validation before actually sending sensitive information in a request.

下列 C# 程式碼說明 SSL 關聯的方法。The following C# code illustrates this method of SSL pinning. ValidateSSLRoot 方法會使用 HttpClient 類別來執行 HTTP 要求。The ValidateSSLRoot method uses the HttpClient class to execute an HTTP request. 在用戶端傳送回應後,它會使用 RequestMessage.TransportInformation.ServerIntermediateCertificates 集合來檢查伺服器傳回的憑證。After the client sends the response, it uses the RequestMessage.TransportInformation.ServerIntermediateCertificates collection to inspect the certificates returned by the server. 然後,用戶端可以使用憑證鏈結中的指紋,來驗證整個憑證鏈結。The client can then validate the entire certificate chain with the thumbprints it has included. 這個方法不會在伺服器憑證過期及更新時,要求更新應用程式中的憑證指紋。This method does require the certificate thumbprints to be updated in the app when the server certificate expires and is renewed.

private async Task ValidateSSLRoot()
{
    // Send a get request to Bing
    var httpClient = new HttpClient();
    var bingUri = new Uri("https://www.bing.com");
    HttpResponseMessage response = 
        await httpClient.GetAsync(bingUri);

    // Get the list of certificates that were used to
    // validate the server's identity
    IReadOnlyList<Certificate> serverCertificates = response.RequestMessage.TransportInformation.ServerIntermediateCertificates;
  
    // Perform validation
    if (!ValidateCertificates(serverCertificates))
    {
        // Close connection as chain is not valid
        return;
    }
    // Validation passed, continue with connection to service
}

private bool ValidateCertificates(IReadOnlyList<Certificate> certs)
{
    // In this example, we iterate through the certificates
    // and check that the chain contains
    // one specific certificate we are expecting
    foreach (var cert in certs)
    {
        byte[] thumbprint = cert.GetHashValue();

        // Check if the thumbprint matches whatever you 
        // are expecting
        var expected = new byte[] { 212, 222, 32, 208, 94, 102, 
            252, 83, 254, 26, 80, 136, 44, 120, 219, 40, 82, 202, 
            228, 116 };

        // ThumbprintMatches does the byte[] comparison 
        if (ThumbprintMatches(thumbprint, expected))
        {
            return true;
        }
    }
    return false;
}

3.3 發佈 REST API 和保護 REST API 的存取3.3 Publishing and securing access to REST APIs

為確保 Web 服務的存取已經過授權,服務必須在每次 API 呼叫時要求驗證。To ensure authorized access to web services, they must require authentication every time an API call is made. 當 Web 服務在網路上公開時,能夠控制效能及範圍也是值得考量的地方。Being able to control performance and scale is also something to consider when web services are exposed across the web. Azure API Management 是能協助您在網路上公開 API 的服務,它依照三個層級來提供功能。Azure API Management is a service that can help expose APIs across the web, while providing features on three levels.

API 的發行者/系統管理員可輕鬆地透過 Azure API Management 的發行者入口網站來設定 API。Publishers/Administrators of the API can easily configure the API through the Publisher Portal of Azure API Management. 他們可以在這裡建立 API 組,以及管理哪些人有哪些 API 的存取權。Here, API sets can be created and access to them can be managed to control who has access to which APIs.

想存取這些 API 的開發人員,可以透過開發人員入口網站提出要求,入口網站可能會立刻提供存取權,或是要求發行者/系統管理員來核准。Developers wanting access to these APIs can make requests through the Developer Portal, which can either immediately provide access or require approval by the publisher/administrator. 開發人員也可以在開發人員入口網站檢視 API 文件和範例程式碼,以便能迅速開始使用 Web 服務所提供的 API。Developers can also view the API documentation and sample code in the Developer Portal, to rapidly adopt the APIs offered by the web service.

這些開發人員所建立,然後透過 Azure API Management 提供的 Proxy 來存取 API 的 appThe apps that these developers create then access the API through the proxy offered by Azure API Management. Proxy 提供一層保護,隱藏 API 在發行者/系統管理員的伺服器上實際的端點,它同時也包含額外的邏輯 (例如 API 轉譯),來確保已公開的 API 在針對某個 API 的呼叫被重新導向到另一個 API 時,能夠保持一致。The proxy both provides a layer of obscurity, hiding the actual end-point of the API on the publisher/administrator’s server and can also include additional logic like API translation to ensure the exposed API is kept consistent when a call to one API is redirected to another. 它也能使用 IP 篩選功能封鎖來自特定 IP 網域或網域組的 API 呼叫。It can also use IP filtering to block API calls originating from a specific IP domain or set of domains. Azure API Management 也利用稱為 API 金鑰的公開金鑰組來驗證和授權每個 API 呼叫,以便保護自己的 Web 服務。Azure API Management also keeps its web services secure by using a set of public keys, called API keys, to authenticate and authorize each API call. 當授權失敗時,系統就會封鎖對於 API 及其支援功能的存取。When authorization fails, access to the API and the functionality it supports is blocked.

Azure API Management 也能減少針對某個服務的 API 呼叫數量 (稱為節流的程序),以便讓 Web 服務的效能最佳化。Azure API Management can also reduce the number of API calls to a service (a procedure called throttling) to optimizes the performance of the web service. 如要深入了解,請參閱 Azure API Management2015 年 AzureCon 中的 Azure API ManagementTo learn more, review Azure API Management and Azure API Management at AzureCon 2015.

4 靜態資料的安全性方法4 Data-at-rest security methods

當資料抵達裝置後,我們將這些資料稱為「靜態資料」。When data arrives on a device, we refer to it as "data-at-rest." 這種資料必須以安全的方式儲存在裝置上,讓未經授權的使用者或應用程式無法存取這些資訊。This data needs to be stored on the device in a secure manner, so that it cannot be accessed by unauthorized users or apps. Windows 10 中的應用程式模型會執行許多工作,來確保任何應用程式所儲存的資料只有該應用程式才能存取,同時在需要時提供 API 來共用資料。The app model in Windows 10 does a lot to ensure that the data stored by any app is only accessible to that app, while providing APIs to share the data when necessary. 還有其他 API 可用來確保資料能夠加密,且認證可以安全地儲存。Additional APIs are also available to ensure that data can be encrypted and credentials can be stored safely.

4.1 Windows 應用程式模型4.1 Windows app model

Windows 過去從來沒有為應用程式下過定義。Traditionally, Windows has never had a definition of an app. 它之前最常被稱為可執行檔 (.exe),且從未包含安裝、儲存體狀態、執行長度、版本設定、作業系統整合,或是 app 之間的通訊。It was most commonly referred to as an executable (.exe), and this never included installation, storage of state, execution length, versioning, OS integration, or app-to-app communication. 通用 Windows 平台模型為應用程式模型下了定義,其定義涵蓋安裝、執行階段環境、資源管理、更新、資料模型,以及解除安裝。The Universal Windows Platform model defines an app model that covers installation, runtime environment, resource management, updates, data model, and uninstallation.

Windows 10 應用程式在容器中執行,這代表它們的預設權限有限 (使用者可以要求及授與額外的權限)。Windows 10 apps run in a container, which means that they have limited privileges by default (additional privileges can be requested and granted by the user). 舉例來說,如果應用程式要存取系統中的檔案,則必須使用 Windows.Storage.Pickers 命名空間的檔案選擇器 ,來讓使用者挑選檔案 (而非啟用直接存取檔案的權限)。For example, if an app wants to access files on the system, a file picker from the Windows.Storage.Pickers namespace has to be used to let the user pick a file (no direct access to files is enabled). 我們再舉一個範例,如果應用程式要存取使用者的位置資料,它必須讓裝置的定位功能需求受到宣告,讓使用者在下載應用程式時,提示使用者該應用程式需要存取使用者的位置資訊。Another example is if an app wants to access the user’s location data, it needs to enable the location device capability needs to be declared, prompting the user at download time that this app will request access to the user’s location. 除此之外,應用程式第一次要存取使用者的位置時,系統會顯示額外的同意提示,要求存取該資料的權限。On top of that, the first time the app wants to access the user’s location, an additional consent prompt is shown to the user, requesting permission to access the data.

請注意,這個應用程式模型就像是應用程式的「監獄」,代表應用程式無法接觸外界,但它並非無法從外界接觸的「城堡」(擁有系統管理員權限的應用程式當然仍舊可以向內接觸)。Note that this app model acts as a "jail" for apps, meaning that they can’t reach out, but it is not a “castle” that cannot be reached from the outside (applications with administrator privileges can of course still reach in). Windows 10 中的 Device Guard,可讓組織/IT 人員指定可執行的 (Win32) app,能進一步協助限制這項存取權。Device Guard in Windows 10, which enables organizations/IT to specify which (Win32) apps are allowed to execute, can further help limit this access.

應用程式模型也會管理應用程式的週期。The app model also manages the app lifecycle. 它預設會限制應用程式的背景執行,例如在應用程式一進入背景時,就暫停應用程式的處理程序 (但會先給應用程式短暫的時間在程式碼中提及自己遭到暫停),並凍結應用程式的記憶體。It limits the background execution of apps by default, for example; as soon as an app goes into the background, the process is suspended – after giving the app a brief period to address app suspension in code – and its memory is frozen. 作業系統不提供讓應用程式要求執行特定背景工作的機制,無論該工作是已經排定、是各種事件 (例如網際網路/藍牙連線、電源變更等) 所觸發,還是屬於特定的案例 (例如播放音樂或使用 GPS 追蹤功能)。The operating system does provide mechanisms for apps to ask for specific background task execution (on a schedule, triggered by various events such as Internet/Bluetooth connectivity, power changes, etc., and in specific scenarios such as music playing or GPS tracking).

當裝置上的記憶體資源不足時,Windows 會終止應用程式以釋放記憶體空間。When memory resources on the device are running low, Windows frees memory space by terminating apps. 這個週期模型會強制應用程式在暫停時保存資料,因為從暫停到終止之間並沒有任何額外的時間。This lifecycle model forces apps to persist data whenever they’re suspended, because there is no additional time available between suspension and termination.

如需詳細資訊,請參閱這是通用的:了解 Windows 10 應用程式的週期For more information, see It's Universal: Understanding the Lifecycle of a Windows 10 Application.

4.2 已儲存認證的保護4.2 Stored credential protection

會存取已驗證服務的 Windows 應用程式,通常會提供讓使用者將認證儲存在本機裝置上的選項。Windows apps that access authenticated services often provide the users the option of storing their credentials on the local device. 這對使用者而言很方便;當他們提供使用者名稱與密碼之後,應用程式就會在後續啟動時自動使用這些資訊。This is a convenience for the users; when they provide their username and password, the app automatically uses them in subsequent launches of the app. 但如果讓攻擊者取得這項已儲存的資料,可能會帶來安全上的問題,因此 Windows 10 提供讓 Windows 應用程式把使用者認證儲存在安全的認證保險箱中的能力。Because this can be a security issue if an attacker gains access to this stored data, Windows 10 provides the ability for Windows apps to store user credentials in a secure credential locker. 應用程式會呼叫認證保險箱 API 來儲存及擷取認證保險箱中的認證,而不是將認證儲存在應用程式的儲存體容器中。The app calls the Credential Locker API to store and retrieve the credentials from the locker instead of storing them in the app’s storage container. 認證保險箱是由作業系統所管理的,但只有儲存認證的的應用程式才能存取,這為認證儲存提供了安全管理的解決方案。The credential locker is managed by the operating system, but access is limited to the app that stores them, providing a securely managed solution for credential storage.

當使用者提供要儲存的認證時,app 會使用 Windows.Security.Credentials 命名空間中的 PasswordVault 物件,來取得認證保險箱的參照。When a user supplies the credentials to be stored, the app gets a reference to the credential locker using the PasswordVault object in the Windows.Security.Credentials namespace. 它接著會建立包含 Windows app 識別碼和使用者名稱及密碼的 PasswordCredential 物件。It then creates a PasswordCredential object containing an identifier for the Windows app and the username and password. 該物件會傳遞給 PasswordVault.Add 方法,以便在保險箱儲存認證。This is passed to the PasswordVault.Add method to store the credentials in the locker. 下列 C# 程式碼範例示範如何完成此作業。The following C# code example shows how this is done.

var vault = new PasswordVault();
vault.Add(new PasswordCredential("My App", username, password));

在下列 C# 程式碼範例中,應用程式會呼叫 PasswordVault 物件的 FindAllByResource 方法,以要求對應到該應用程式的所有認證。In the following C# code example, the app requests all of the credentials corresponding to the app by calling the FindAllByResource method of the PasswordVault object. 如果傳回多個認證,應用程式會提示使用者輸入自己的使用者名稱。If more than one is returned, it prompts the user to enter their username. 如果保險箱內沒有認證,應用程式會提示使用者輸入認證。If the credentials are not in the locker, the app prompts the user for them. 然後,使用者便會使用認證登入伺服器。The user is then logged into the server using the credentials.

private string resourceName = "My App";
private string defaultUserName;

private void Login()
{
    PasswordCredential loginCredential = GetCredentialFromLocker();

    if (loginCredential != null)
    {
        // There is a credential stored in the locker.
        // Populate the Password property of the credential
        // for automatic login.
        loginCredential.RetrievePassword();
    }
    else
    {
        // There is no credential stored in the locker.
        // Display UI to get user credentials.
        loginCredential = GetLoginCredentialUI();
    }
    // Log the user in.
    ServerLogin(loginCredential.UserName, loginCredential.Password);
}

private PasswordCredential GetCredentialFromLocker()
{
    PasswordCredential credential = null;

    var vault = new PasswordVault();
    var credentialList = vault.FindAllByResource(resourceName);

    if (credentialList.Count == 1)
    {
        credential = credentialList[0];
    }
    else if (credentialList.Count > 0)
    {
        // When there are multiple usernames,
        // retrieve the default username. If one doesn't
        // exist, then display UI to have the user select
        // a default username.
        defaultUserName = GetDefaultUserNameUI();

        credential = vault.Retrieve(resourceName, defaultUserName);
    }
    return credential;
}

如需詳細資訊,請參閱認證保險箱For more information, see Credential locker.

4.3 已儲存資料的保護4.3 Stored data protection

當您在處理已儲存的資料 (通常稱為靜態資料) 時,為這些資料加密即可防止未經授權的使用者存取已儲存的資料。When you are dealing with stored data, commonly referred to as data-at-rest, encrypting it can prevent unauthorized users from accessing the stored data. 為資料加密的兩個常見機制,就是使用對稱金鑰或使用非對稱金鑰。The two common mechanisms to encrypt data are using either symmetric keys or using asymmetric keys. 不過,資料加密無法確保資料從傳送到儲存的這段時間中不會遭到修改。However, data encryption can’t ensure that the data is unaltered between the time it was sent and the time it was stored. 換句話說,這種方法無法確保資料完整性。In other words, the data integrity cannot be ensured. 使用訊息驗證碼、雜湊及數位簽章,是解決這種問題的常見技術。Using message authentication codes, hashes, and digital signing are common techniques to solve this problem.

4.3.1 資料加密4.3.1 Data encryption

使用對稱式加密時,寄件者與收件者都有相同的金鑰,並使用該金鑰來為資料加密及解密。With symmetric encryption, both the sender and recipient have the same key and use it to both encrypt and decrypt the data. 這個方法的挑戰在於安全地分享金鑰,讓雙方都知道自己有該金鑰。The challenge with this approach is securely sharing the key so both parties are aware of it.

而其中一個解決方法,就是使用公開/私密金鑰的非對稱式加密。One answer to this is asymmetric encryption, in which a public/private key pair is used. 公開金鑰可自由地與任何想要為訊息加密的使用者分享。The public key is shared freely with anyone who wants to encrypt a message. 私密金鑰則會永遠保密,只有您可以使用它來為資料解密。The private key is always kept secret so that only you can use it to decrypt the data. 有種允許尋找公開金鑰的常見技術,就是使用數位憑證 (或是簡單稱為憑證)。A common technique to allow for discovery of the public key is by using digital certificates, also simply referred to as certificates. 憑證除了包含使用者或伺服器的相關資訊 (例如名稱、簽發者、電子郵件地址和國家/地區) 之外,也包含公開金鑰的相關資訊。The certificate holds information about the public key, in addition to information about the user or server such as the name, issuer, email address and country.

Windows app 開發人員可以使用 SymmetricKeyAlgorithmProviderAsymmetricKeyAlgorithmProvider 類別,在自己的 UWP app 中使用對稱式和非對稱式加密。Windows app developers can use the SymmetricKeyAlgorithmProvider and AsymmetricKeyAlgorithmProvider classes to implement symmetric and asymmetric encryption in their UWP apps. 此外, CryptographicEngine 類別可以用來加密和解密資料、簽入內容和確認數位簽章。Additionally, the CryptographicEngine class can be used to encrypt and decrypt data, sign content and verify digital signatures. App 也可以使用 Windows.Security.Cryptography.DataProtection 命名空間中的 DataProtectionProvider 類別來加密和解密儲存的本機資料。Apps can also use the DataProtectionProvider class in the Windows.Security.Cryptography.DataProtection namespace to encrypt and decrypt stored local data.

4.3.2 偵測訊息竄改 (MAC、雜湊以及簽章)4.3.2 Detecting message tampering (MACs, hashes, and signatures)

MAC 是使用對稱金鑰 (稱為祕密金鑰) 產生的程式碼 (或標記),或做為 MAC 加密演算法輸入的訊息。A MAC is a code (or tag) that results from using a symmetric key (called the secret key) or a message as input to a MAC encryption algorithm. 寄件者及收件者要同意祕密金鑰及演算法,才會開始訊息傳輸。The secret key and the algorithm are agreed upon by the sender and receiver before the message transfer.

MAC 會確認訊息,就像這樣。MACs verify messages like this.

  • 寄件者使用祕密金鑰做為 MAC 演算法的輸入,以衍生 MAC 標記。The sender derives the MAC tag by using the secret key as input to the MAC algorithm.
  • 寄件者將 MAC 標記及訊息傳送給收件者。The sender sends the MAC tag and the message to the receiver.
  • 收件者使用祕密金鑰與訊息做為 MAC 演算法的輸入,以衍生 MAC 標記。The receiver derives the MAC tag by using the secret key and the message as inputs to the MAC algorithm.
  • 收件者比較其 MAC 標記與寄件者的 MAC 標記。The receiver compares their MAC tag with the sender's MAC tag. 如果這兩者相同,我們便知道該訊息並未遭到竄改。If they are the same then we know that the message has not been tampered with.

mac 驗證

Windows 應用程式可以實行 MAC 訊息驗證,方法是呼叫 MacAlgorithmProvider 類別來產生金鑰,以及呼叫 CryptographicEngine 類別來執行 MAC 加密演算法。Windows apps can implement MAC message verification by calling the MacAlgorithmProvider class to generate the key and CryptographicEngine class to perform the MAC encryption algorithm.

4.3.3 使用雜湊4.3.3 Using hashes

雜湊函數是使用任意長度的資料區塊的密碼編譯演算法,會傳回一個固定大小位元字串,稱為雜湊值。A hash function is a cryptographic algorithm that takes an arbitrarily long block of data and returns a fixed-size bit string called a hash value. 有一整個系列的雜湊函數可以執行這項操作。There is an entire family of hash functions that can do this.

雜湊值可用來取代上述訊息傳輸案例中的 MAC。A hash value can be used in place of a MAC in the message-transfer scenario above. 寄件者會傳送雜湊值和一則訊息,收件者從寄件者的雜湊值和訊息衍生其雜湊值,並比較兩個雜湊值。The sender sends a hash value and a message, and the receiver derives their own hash value from the sender's hash value and message and compares the two hash values. Windows 10 上執行的 app 可以呼叫 HashAlgorithmProvider 類別來列舉可用的雜湊演算法,並執行其中一個演算法。Apps running on Windows 10 can call the HashAlgorithmProvider class to enumerate the hash algorithms that are available and run one of them. CryptographicHash 類別代表雜湊值。The CryptographicHash class represents the hash value. CryptographicHash.GetValueAndReset 方法可以用來重複雜湊不同的資料,而不用在每次使用時都要重新建立物件。The CryptographicHash.GetValueAndReset method can be used to repeatedly hash different data without having to re-create the object for each use. CryptographicHash 類別的 Append 方法會將新資料加入要雜湊的緩衝區。The Append method of the CryptographicHash class adds new data to a buffer to be hashed. 下列 C# 程式碼範例將示範這整個過程。This entire process is shown in the following C# code example.

public void SampleReusableHash()
{
    // Create a string that contains the name of the
    // hashing algorithm to use.
    string strAlgName = HashAlgorithmNames.Sha512;

    // Create a HashAlgorithmProvider object.
    HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

    // Create a CryptographicHash object. This object can be reused to continually
    // hash new messages.
    CryptographicHash objHash = objAlgProv.CreateHash();

    // Hash message 1.
    string strMsg1 = "This is message 1";
    IBuffer buffMsg1 = CryptographicBuffer.ConvertStringToBinary(strMsg1, BinaryStringEncoding.Utf16BE);
    objHash.Append(buffMsg1);
    IBuffer buffHash1 = objHash.GetValueAndReset();

    // Hash message 2.
    string strMsg2 = "This is message 2";
    IBuffer buffMsg2 = CryptographicBuffer.ConvertStringToBinary(strMsg2, BinaryStringEncoding.Utf16BE);
    objHash.Append(buffMsg2);
    IBuffer buffHash2 = objHash.GetValueAndReset();

    // Convert the hashes to string values (for display);
    string strHash1 = CryptographicBuffer.EncodeToBase64String(buffHash1);
    string strHash2 = CryptographicBuffer.EncodeToBase64String(buffHash2);
}

4.3.4 數位簽章4.3.4 Digital signatures

數位簽署的儲存訊息的資料完整性是以類似 MAC 驗證的方式驗證。The data integrity of a digitally signed stored message is verified in a similar way to MAC authentication. 以下是數位簽章工作流程運作的方式。Here is the way the digital signature workflow operates.

  • 寄件者使用訊息做為雜湊演算法的輸入,以衍生雜湊值 (也稱為摘要)。The sender derives a hash value (also known as a digest) by using the message as the input to a hash algorithm.
  • 寄件者使用他們的私密金鑰加密摘要。The sender encrypts the digest using their private key.
  • 寄件者會傳送訊息、加密的摘要,以及所使用的雜湊演算法的名稱。The sender sends the message, the encrypted digest, and the name of the hash algorithm that was used.
  • 收件者使用公開金鑰來解密其收到的加密摘要。The receiver uses the public key to decrypt the encrypted digest it received. 然後使用雜湊演算法雜湊訊息,以建立自己的摘要。It then uses the hash algorithm to hash the message to create a digest of its own. 最後,收件者會比較這兩個摘要 (其收到和解密的,以及其所建立的)。And finally the receiver compares the two digests (the one it received and decrypted, and the one it made). 只有在這兩者相符時,收件者才能確定訊息是由私密金鑰的擁有人傳送的,因此對方的確是他們聲稱的人,且訊息在傳輸過程中並未遭到修改。Only if the two match can the receiver be sure that the message was sent by the possessor of the private key, and therefore they are who they say they are, and that the message was not altered in transit.

數位簽章

雜湊演算法的速度非常快,即使是處理大型訊息時也能迅速衍生雜湊值。Hashing algorithms are very fast, so hash values can be derived quickly from even large messages. 產生的雜湊值長度不一,可能會比完整訊息還要短,因此最佳做法是使用公開金鑰和私密金鑰來只為摘要加密及解密,而非為完整的訊息。The resulting hash value is an arbitrary length and can be shorter than the full message, so using public and private keys to encrypt and decrypt only the digest rather than the full message is an optimization.

如需詳細資訊,請參閱數位簽章MAC、雜湊以及簽章,以及密碼編譯For more information, take a look articles on Digital signatures, MACs, hashes, and signatures, and Cryptography.

5 總結5 Summary

Windows 10 的通用 Windows 平台提供數種方式,讓您能利用作業系統的功能來建立更安全的應用程式。The Universal Windows Platform in Windows 10 offers a number of ways to leverage operating system capabilities to create more secure apps. 在不同的驗證案例中 (例如單一因素驗證、多重要素驗證,或利用 OAuth 識別提供者的代理驗證),API 可用來減少在驗證方面最常見的挑戰。In different authentication scenarios, such as single-factor, multi-factor, or brokered authentication with an OAuth identity provider, APIs exist to mitigate the most common challenges with authentication. Windows Hello 提供新的生物特徵識別登入系統來辨識使用者,以及主動防禦規避適當身分識別程序的攻擊。Windows Hello provides a new biometric sign-in system that recognizes the user and actively defeats efforts to circumvent proper identification. 它也會提供多層按鍵及不可以洩露或在信賴平台模組外部使用的憑證。It also delivers multiple layers of keys and certificates that can never be revealed or used outside the trusted platform module. 此外,透過選用的證明識別金鑰和憑證,能進一步提高安全性層級。Plus, a further layer of security is available through the optional use of attestation identity keys and certificates.

如要保護傳輸中的資料,可使用 API 來透過 SSL 與遠端系統安全地通訊,它還提供利用 SSL 關聯來驗證伺服器真確性的可能性。To secure data in flight, APIs exist to communicate with remote systems securely over SSL, while providing the possibility to validate the server’s authenticity with SSL pinning. Azure API Management 能協助您以受控制的方式安全地發佈 API,因為它使用能提供額外的 API 端點混淆的 Proxy,為在網路上公開 API 提供強大的設定選項。Publishing APIs securely and in a controlled manner is something in which Azure API Management aids by providing powerful configuration options for exposing APIs across the web using a proxy that provides additional obfuscation of the API endpoint. 您可以使用 API 金鑰來保護這些 API 的存取權,以及調整 API 呼叫來控制效能。Access to these APIs is secured by using API keys and API calls can be throttled to control performance.

當資料抵達裝置時,Windows 應用程式模型在應用程式該如何安裝、更新及存取資料方面提供更大的控制權,同時它還能防止其他應用程式以未經授權的方式存取這些資料。When the data arrives on the device, the Windows app model provides more control over how the app is installed, updated and accesses it data, while keeping it from accessing data of other apps in an unauthorized manner. 由作業系統管理的認證保險箱能為使用者認證提供安全的儲存空間,而其他資料可在裝置上透過使用由通用 Windows 平台提供的加密和雜湊 API 來保護。Credential locker can provide secure storage of user credentials that is managed by the operating system and other data can be protected on the device by using the encryption and hashing APIs offered by the Universal Windows Platform.

6 資源6 Resources

6.1 操作說明文章6.1 How-to articles

6.2 程式碼範例6.2 Code samples

6.3 API 參考6.3 API reference