Windows ML에서 암호화된 모델 사용

LearningModel 클래스에 적용할 수 있는 몇 가지 정적 메서드를 사용하여 앱의 파일, 디스크의 파일에서 모델 로드 또는 스트림에서 모델 로드와 같은 기계 학습 모델을 로드할 수 있습니다.

스트림 메서드에서 로드하면 모델을 보다 효율적으로 제어할 수 있습니다. 이 경우 LoadFromStream 메서드 중 하나를 호출하기 전에 디스크에서 모델을 암호화하고 메모리에서만 암호를 해독하도록 선택할 수 있습니다.

이 자습서에서는 암호화된 기계 학습 모델을 Windows ML 애플리케이션(C#)과 통합하는 방법에 대해 알아봅니다.

Windows ML API는 기계 학습 암호화 서비스를 제공하지 않으며 모든 종류의 손상 또는 손실에 대해 책임을 지지 않습니다.

ONNX 모델 가져오기

이 자습서에서는 ONNX 형식의 SqueezeNet 모델을 사용하여 스트림에서 암호화, 암호 해독 및 로드를 수행합니다.

GitHub에서 SqueezeNet 개체 감지 샘플 앱을 다운로드하거나 복제하여 SqueezeNet.onnx 모델을 가져옵니다.

필요한 선언 및 변수 지정

  1. 필요한 모든 API에 액세스하기 위해 아래의 사용 구문을 복사하십시오.
using System;
using System.Threading.Tasks;
using Windows.AI.MachineLearning;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;

키와 초기화 벡터에 대한 두 개의 특수 변수를 정의합니다.

는 대칭(또는 비대칭) 키 쌍을 나타내는 CryptographicKey 클래스의 변수입니다. 이 메서드를 사용하여 키를 만들거나 가져오기 때문에 이 클래스의 개체가 AsymmetricKeyAlgorithmProvider 필요합니다.

초기화 벡터는 바이트 스트림 읽기 및 쓰기 인터페이스에서 사용되는 참조된 바이트 배열을 나타내는 IBuffer 클래스의 변수입니다.

CryptographicKey 두 클래스 변수는 스트림 IBuffer 을 암호화하고 암호 해독하는 데 사용됩니다.

  1. 암호화 네임스페이스 내에서 using 문 다음에 다음 변수 선언과 MainPage 클래스를 추가합니다.
namespace crypto
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private CryptographicKey _key;
        private IBuffer _initialization_vector;
        public MainPage()
        {
            this.InitializeComponent();

            Run();
        }
    }
}

모델 암호화

Windows API는 Windows ML API 집합의 기능을 향상시킬 수 있는 다양한 기능 집합을 제공합니다. 여기서는 Windows API 집합에 제공된 암호화 및 암호 해독 서비스를 사용하여 메모리에서 스트림을 생성하고 Windows ML API를 사용하여 해당 스트림에서 모델을 로드합니다.

모든 암호화 서비스를 사용하여 편의상 기계 학습 모델을 암호화할 수 있습니다. 이 자습서에서는 암호화 방법을 SymmetricAlgorithmNames - .AesCbcPkcs7사용합니다.

SymmetricAlgorithmNames 클래스를 사용하면 대칭 키 알고리즘을 검색하여 모델에 대칭 키 암호화를 적용할 수 있습니다. 이 유형의 암호화를 사용하려면 암호화에 사용되는 동일한 키도 암호 해독에 사용해야 합니다.

클래스를 SymmetricKeyAlgorithmProvider 사용하여 알고리즘을 선택하고 키를 만들 수 있습니다. 이 자습서에서는 알고리즘을 .AesCbcPkcs7. 사용합니다.

이 알고리즘은 AES_CBC_PKCS7 암호 블록 연결 작업 모드 및 PKCS#7 패딩과 결합된 고급 AES(암호화 표준) 알고리즘을 나타냅니다.

  1. 아래 코드는 키를 생성하고 모델을 암호화하는 방법을 보여줍니다.
async Task<IBuffer> EncryptAsync(StorageFile model_file)
{
	// get a buffer for the model file
	var file_buffer = await Windows.Storage.FileIO.ReadBufferAsync(model_file);

	// set up the encryption algorithm
	var algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
	uint key_length = 32;
	var key_buffer = CryptographicBuffer.GenerateRandom(key_length);
	_key = algorithm.CreateSymmetricKey(key_buffer);
	_initialization_vector = CryptographicBuffer.GenerateRandom(algorithm.BlockLength);

	// perform the encryption
	var encrypted_buffer = CryptographicEngine.Encrypt(_key, file_buffer, _initialization_vector);

	return encrypted_buffer;
}

[참고!] 암호화 키에 대해 자세히 알아보고 싶나요? 암호화 키 설명서를 검토하세요.

스트림에서 모델을 해독하고 로드하세요.

모델을 로드하기 전에 CryptographicEngine.Decrypt 메서드를 사용하여 암호를 해독해야 합니다. CryptographicEngine.Decrypt 는 대칭 또는 비대칭 알고리즘을 사용하여 이전에 암호화된 콘텐츠의 암호를 해독하는 방법입니다. 메서드를 호출할 때 이전에 생성된 키를 제공해야 합니다.

암호 해독된 모델에 액세스하려면 디스크 대신 메모리에 저장된 입력 및 출력 스트림의 데이터에 임의로 액세스하는 클래스를 사용합니다 InMemoryRandomAccessStream .

마지막 단계로, 메서드를 사용하여 LearningModel.LoadFromStreamAsync 스트림에서 모델을 로드하는 세션을 만듭니다. 이 메서드를 동기 또는 비동기 작업으로 호출할 수 있습니다.

아래 코드는 생성된 키를 사용하여 모델의 암호를 해독하고, 스트림에 쓴 다음, 스트림에서 모델을 로드하는 방법을 보여줍니다.

async Task DecryptAndRunAsync(IBuffer encryptyed_buffer)
{
	// decrypt the buffer
	var decrypted_buffer = CryptographicEngine.Decrypt(_key, encryptyed_buffer, _initialization_vector);

	// write it to a stream
	var decrypted_stream = new InMemoryRandomAccessStream();
	await decrypted_stream.WriteAsync(decrypted_buffer);

	// load the model from the stream
	var model = await LearningModel.LoadFromStreamAsync(RandomAccessStreamReference.CreateFromStream(decrypted_stream));

	// create a session
	var session = new LearningModelSession(model);
}

모델 실행

다음 Run 메서드를 복사하여 앞에서 정의한 메서드를 호출합니다.

async Task Run()
{

	// get the model file
	var model_file = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/SqueezeNet.onnx"));

	// encrypt the model file.
	var encryptyed_buffer = await EncryptAsync(model_file);

	// decrypt the model file and load it
	await DecryptAndRunAsync(encryptyed_buffer);
}

요약

완료! Windows ML 앱에 모델을 성공적으로 로드했습니다.

모델을 로드한 후 세션을 계속 만들고, 모델 입력 및 출력을 바인딩하고, 모델을 평가하여 Windows ML 앱을 완료할 수 있습니다.

추가 리소스

이 자습서에서 언급한 항목에 대해 자세히 알아보려면 다음 리소스를 방문하세요.