Android kodu örnekleri

Önemli

Mart 2020'den önce yayımlanan Microsoft Rights Management Service SDK sürümleri kullanım dışı bırakılmıştır; önceki sürümleri kullanan uygulamaların Mart 2020 sürümünü kullanacak şekilde güncelleştirilmiş olması gerekir. Tüm ayrıntılar için kullanımdan kaldırma bildirimine bakın.

Microsoft Rights Management Service SDK'sı için başka geliştirme planlanmıyor. Sınıflandırma, etiketleme ve koruma hizmetleri için Microsoft Bilgi Koruması SDK'sının benimsenmesini kesinlikle öneririz.

Bu makalede, RMS SDK'nın Android sürümü için öğeleri kodlama gösterilmektedir.

Not Bu makalede MSIPC (Microsoft Bilgi Koruması ve Denetim) terimi istemci işlemini ifade eder.

Microsoft Rights Management SDK 4.2’yi kullanma - önemli senaryolar

Bu kod örnekleri, bu SDK'ya yönlendirmeniz için önemli olan geliştirme senaryolarını temsil eden daha büyük bir örnek uygulamadan alınır. Aşağıdakilerin nasıl kullanılacağını gösterir:

  • Korumalı dosya olarak da adlandırılan Microsoft Korumalı Dosya biçimi.
  • Özel korumalı dosya biçimleri
  • Özel kullanıcı arabirimi (UI) denetimleri

MSIPCSampleApp örnek uygulaması, Android işletim sistemi için bu SDK ile kullanılabilir. Daha fazla bilgi edinmek için bkz. rms-sdk-ui-for-android.

Senaryo: RMS korumalı dosya kullanma

  • 1. Adım: ProtectedFileInputStream oluşturma.

    Kaynak: MsipcAuthenticationCallback.java

    Açıklama: ProtectedFileInputStream nesnesinin örneğini oluşturun ve hizmet kimlik doğrulamasını uygulayın. AuthenticationRequestCallback örneğini mRmsAuthCallback parametresi olarak MSIPC API'sine geçirerek belirteç almak için AuthenticationRequestCallback kullanın. Aşağıdaki örnek kod bölümünün sonlarında bulunan ProtectedFileInputStream.create çağrısına bakın.

        public void startContentConsumptionFromPtxtFileFormat(InputStream inputStream)
        {
            CreationCallback<ProtectedFileInputStream> protectedFileInputStreamCreationCallback =
              new CreationCallback<ProtectedFileInputStream>()
            {
                @Override
                public Context getContext()
                {
                   …
               }
    
                @Override
                public void onCancel()
                {
                   …
                }
    
                @Override
                public void onFailure(ProtectionException e)
                {
                   …
                }
    
                @Override
                public void onSuccess(ProtectedFileInputStream protectedFileInputStream)
                {
                   …
                   …
                    byte[] dataChunk = new byte[16384];
                    try
                    {
                        while ((nRead = protectedFileInputStream.read(dataChunk, 0,
                                dataChunk.length)) != -1)
                        {
                            …
                        }
                         …
                        protectedFileInputStream.close();
                    }
                    catch (IOException e)
                    {
                      …
                    }
              }
            };
            try
            {
               …
                ProtectedFileInputStream.create(inputStream, null, mRmsAuthCallback,
                                                PolicyAcquisitionFlags.NONE,
                                                protectedFileInputStreamCreationCallback);
            }
            catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e)
            {
                …
            }
        }
    
  • 2. Adım: Active Directory Kimlik Doğrulama Kitaplığı'nı (ADAL) kullanarak kimlik doğrulamasını ayarlayın.

    Kaynak: MsipcAuthenticationCallback.java.

    Açıklama: Bu adım, örnek kimlik doğrulama parametreleriyle authenticationRequestCallback uygulamak için ADAL kullanır. Daha fazla bilgi edinmek için bkz. Azure AD Kimlik Doğrulama Kitaplığı (ADAL).

         class MsipcAuthenticationCallback implements AuthenticationRequestCallback
         {
    
         …
    
         @Override
         public void getToken(Map<String, String> authenticationParametersMap,
                              final AuthenticationCompletionCallback authenticationCompletionCallbackToMsipc)
         {
             String authority = authenticationParametersMap.get("oauth2.authority");
             String resource = authenticationParametersMap.get("oauth2.resource");
             String userId = authenticationParametersMap.get("userId");
             final String userHint = (userId == null)? "" : userId;
             AuthenticationContext authenticationContext = App.getInstance().getAuthenticationContext();
             if (authenticationContext == null || !authenticationContext.getAuthority().equalsIgnoreCase(authority))
             {
                 try
                 {
                     authenticationContext = new AuthenticationContext(App.getInstance().getApplicationContext(), authority, …);
                     App.getInstance().setAuthenticationContext(authenticationContext);
                 }
                 catch (NoSuchAlgorithmException e)
                 {
                     …
                     authenticationCompletionCallbackToMsipc.onFailure();
                 }
                 catch (NoSuchPaddingException e)
                 {
                     …
                     authenticationCompletionCallbackToMsipc.onFailure();
                 }
            }
             App.getInstance().getAuthenticationContext().acquireToken(mParentActivity, resource, mClientId, mRedirectURI, userId, mPromptBehavior,
                            "&USERNAME=" + userHint, new AuthenticationCallback<AuthenticationResult>()
                             {
                                 @Override
                                 public void onError(Exception exc)
                                 {
                                     …
                                     if (exc instanceof AuthenticationCancelError)
                                     {
                                          …
                                         authenticationCompletionCallbackToMsipc.onCancel();
                                     }
                                     else
                                     {
                                          …
                                         authenticationCompletionCallbackToMsipc.onFailure();
                                     }
                                 }
    
                                 @Override
                                 public void onSuccess(AuthenticationResult result)
                                 {
                                     …
                                     if (result == null || result.getAccessToken() == null
                                             || result.getAccessToken().isEmpty())
                                     {
                                          …
                                     }
                                     else
                                     {
                                         // request is successful
                                         …
                                         authenticationCompletionCallbackToMsipc.onSuccess(result.getAccessToken());
                                     }
                                 }
                             }
    
                             );
                       }
    
  • 3. Adım: UserPolicy.accessCheck metodu aracılığıyla bu kullanıcı için bu içerikte Düzenleme hakkının olup olmadığını denetleyin.

    Kaynak: TextEditorFragment.java

         //check if user has edit rights and apply enforcements
                if (!mUserPolicy.accessCheck(EditableDocumentRights.Edit))
                {
                    mTextEditor.setFocusableInTouchMode(false);
                    mTextEditor.setFocusable(false);
                    mTextEditor.setEnabled(false);
                    …
                }
    

Senaryo: Bir şablon kullanarak yeni bir korumalı dosya oluşturma

Bu senaryo, bir şablonlar listesi alınarak, birincisi seçilip bir ilke oluşturularak başlar, ardından yeni korumalı dosya oluşturulur ve bu dosyaya yazılır.

  • 1. adım: Bir TemplateDescriptor nesnesi aracılığıyla şablon listesini alın.

    Kaynak: MsipcTaskFragment.java

    CreationCallback<List<TemplateDescriptor>> getTemplatesCreationCallback = new CreationCallback<List<TemplateDescriptor>>()
      {
          @Override
          public Context getContext()
          {
              …
          }
    
          @Override
          public void onCancel()
          {
              …
          }
    
          @Override
          public void onFailure(ProtectionException e)
          {
              …
          }
    
          @Override
          public void onSuccess(List<TemplateDescriptor> templateDescriptors)
          {
             …
          }
      };
      try
      {
              …
          mIAsyncControl = TemplateDescriptor.getTemplates(emailId, mRmsAuthCallback, getTemplatesCreationCallback);
      }
      catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e)
      {
              …
      }
    
  • 2. Adım: Listedeki birinci şablonu kullanarak bir UserPolicy oluşturun.

    Kaynak: MsipcTaskFragment.java

      CreationCallback<UserPolicy> userPolicyCreationCallback = new CreationCallback<UserPolicy>()
      {
          @Override
          public Context getContext()
          {
              …
          }
    
          @Override
          public void onCancel()
          {
              …
          }
    
          @Override
          public void onFailure(ProtectionException e)
          {
              …
          }
    
          @Override
          public void onSuccess(final UserPolicy item)
          {
              …
          }
      };
      try
      {
           …
          mIAsyncControl = UserPolicy.create((TemplateDescriptor)selectedDescriptor, mEmailId, mRmsAuthCallback,
                            UserPolicyCreationFlags.NONE, userPolicyCreationCallback);
           …
      }
      catch (InvalidParameterException e)
      {
              …
      }
    
  • 3. adım: Bir ProtectedFileOutputStream oluşturun ve ona içerik yazın.

    Kaynak: MsipcTaskFragment.java

    private void createPTxt(final byte[] contentToProtect)
        {
             …
            CreationCallback<ProtectedFileOutputStream> protectedFileOutputStreamCreationCallback = new CreationCallback<ProtectedFileOutputStream>()
            {
                @Override
                public Context getContext()
                {
                 …
                }
    
                @Override
                public void onCancel()
                {
                 …
                }
    
                @Override
                public void onFailure(ProtectionException e)
                {
                 …
                }
    
                @Override
                public void onSuccess(ProtectedFileOutputStream protectedFileOutputStream)
                {
                    try
                    {
                        // write to this stream
                        protectedFileOutputStream.write(contentToProtect);
                        protectedFileOutputStream.flush();
                        protectedFileOutputStream.close();
                        …
                    }
                    catch (IOException e)
                    {
                        …
                    }
                }
            };
            try
            {
                File file = new File(filePath);
                outputStream = new FileOutputStream(file);
                mIAsyncControl = ProtectedFileOutputStream.create(outputStream, mUserPolicy, originalFileExtension,
                        protectedFileOutputStreamCreationCallback);
            }
            catch (FileNotFoundException e)
            {
                 …
            }
            catch (InvalidParameterException e)
            {
                 …
            }
        }
    

Senaryo: Özel bir korumalı dosyayı açma

  • 1. Adım: Bir serializedContentPolicy’den bir UserPolicy oluşturun.

    Kaynak: MsipcTaskFragment.java

    CreationCallback<UserPolicy> userPolicyCreationCallbackFromSerializedContentPolicy = new CreationCallback<UserPolicy>()
            {
                @Override
                public void onSuccess(UserPolicy userPolicy)
                {
                  …
                }
    
                @Override
                public void onFailure(ProtectionException e)
                {
                  …
                }
    
                @Override
                public void onCancel()
                {
                  …
                }
    
                @Override
                public Context getContext()
                {
                  …
                }
            };
            try
            {
                ...
    
                // Read the serializedContentPolicyLength from the inputStream.
                long serializedContentPolicyLength = readUnsignedInt(inputStream);
    
                // Read the PL bytes from the input stream using the PL size.
                byte[] serializedContentPolicy = new byte[(int)serializedContentPolicyLength];
                inputStream.read(serializedContentPolicy);
    
                ...
    
                UserPolicy.acquire(serializedContentPolicy, null, mRmsAuthCallback, PolicyAcquisitionFlags.NONE,
                userPolicyCreationCallbackFromSerializedContentPolicy);
            }
            catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e)
            {
            ...
            }
            catch (IOException e)
            {
            ...
            }
    
  • 2. adım: 1. adımdakiUserPolicy’yi kullanarak bir CustomProtectedInputStream oluşturun.

    Kaynak: MsipcTaskFragment.java

      CreationCallback<CustomProtectedInputStream> customProtectedInputStreamCreationCallback = new CreationCallback<CustomProtectedInputStream>()
      {
         @Override
         public Context getContext()
         {
             …
         }
    
         @Override
         public void onCancel()
         {
             …
         }
    
         @Override
         public void onFailure(ProtectionException e)
         {
             …
         }
    
         @Override
         public void onSuccess(CustomProtectedInputStream customProtectedInputStream)
         {
            …
    
             byte[] dataChunk = new byte[16384];
             try
             {
                 while ((nRead = customProtectedInputStream.read(dataChunk, 0, dataChunk.length)) != -1)
                 {
                      …
                 }
                  …
                 customProtectedInputStream.close();
             }
             catch (IOException e)
             {
                …
             }
             …
         }
     };
    
    try
    {
      ...
    
      // Retrieve the encrypted content size.
      long encryptedContentLength = readUnsignedInt(inputStream);
    
      updateTaskStatus(new TaskStatus(TaskState.Starting, "Consuming content", true));
    
      CustomProtectedInputStream.create(userPolicy, inputStream,
                                     encryptedContentLength,
                                     customProtectedInputStreamCreationCallback);
    }
    catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e)
    {
      ...
    }
    catch (IOException e)
    {
      ...
    }
    
  • 3. adım: CustomProtectedInputStream’den içeriği mDecryptedContent’e okuyun ve kapatın.

    Kaynak: MsipcTaskFragment.java

    @Override
    public void onSuccess(CustomProtectedInputStream customProtectedInputStream)
    {
      mUserPolicy = customProtectedInputStream.getUserPolicy();
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    
      int nRead;
      byte[] dataChunk = new byte[16384];
    
      try
      {
        while ((nRead = customProtectedInputStream.read(dataChunk, 0,
                                                            dataChunk.length)) != -1)
        {
           buffer.write(dataChunk, 0, nRead);
        }
    
        buffer.flush();
        mDecryptedContent = new String(buffer.toByteArray(), Charset.forName("UTF-8"));
    
        buffer.close();
        customProtectedInputStream.close();
      }
      catch (IOException e)
      {
        ...
      }
    }
    

Senaryo: Özel ilke kullanarak özel korumalı dosya oluşturma

  • 1. Adım: Kullanıcı tarafından sağlanan bir e-posta adresiyle, bir ilke tanımlayıcısı oluşturun.

    Kaynak: MsipcTaskFragment.java

    Açıklama: Uygulamada, cihaz arabiriminden kullanıcı girişleri kullanılarak aşağıdaki nesneler oluşturulur; UserRights ve PolicyDescriptor.

      // create userRights list
      UserRights userRights = new UserRights(Arrays.asList("consumer@domain.com"),
        Arrays.asList( CommonRights.View, EditableDocumentRights.Print));
      ArrayList<UserRights> usersRigthsList = new ArrayList<UserRights>();
      usersRigthsList.add(userRights);
    
      // Create PolicyDescriptor using userRights list
      PolicyDescriptor policyDescriptor = PolicyDescriptor.createPolicyDescriptorFromUserRights(
                                                             usersRigthsList);
      policyDescriptor.setOfflineCacheLifetimeInDays(10);
      policyDescriptor.setContentValidUntil(new Date());
    
  • 2. Adım: İlke tanımlayıcısı selectedDescriptor’dan bir özel UserPolicy oluşturun.

    Kaynak: MsipcTaskFragment.java

       mIAsyncControl = UserPolicy.create((PolicyDescriptor)selectedDescriptor,
         mEmailId, mRmsAuthCallback, UserPolicyCreationFlags.NONE, userPolicyCreationCallback);
    
  • 3. adım: İçerik oluşturup CustomProtectedOutputStream’e yazın ve sonra kapatın.

    Kaynak: MsipcTaskFragment.java

    File file = new File(filePath);
        final OutputStream outputStream = new FileOutputStream(file);
        CreationCallback<CustomProtectedOutputStream> customProtectedOutputStreamCreationCallback = new CreationCallback<CustomProtectedOutputStream>()
        {
            @Override
            public Context getContext()
            {
              …
            }
    
            @Override
            public void onCancel()
            {
              …
            }
    
            @Override
            public void onFailure(ProtectionException e)
            {
              …
            }
    
            @Override
            public void onSuccess(CustomProtectedOutputStream protectedOutputStream)
            {
                try
                {
                    // write serializedContentPolicy
                    byte[] serializedContentPolicy = mUserPolicy.getSerializedContentPolicy();
                    writeLongAsUnsignedIntToStream(outputStream, serializedContentPolicy.length);
                    outputStream.write(serializedContentPolicy);
                    // write encrypted content
                    if (contentToProtect != null)
                    {
                        writeLongAsUnsignedIntToStream(outputStream,
                                CustomProtectedOutputStream.getEncryptedContentLength(contentToProtect.length,
                                        protectedOutputStream.getUserPolicy()));
                        protectedOutputStream.write(contentToProtect);
                        protectedOutputStream.flush();
                        protectedOutputStream.close();
                    }
                    else
                    {
                        outputStream.flush();
                        outputStream.close();
                    }
                    …
                }
                catch (IOException e)
                {
                  …
                }
            }
        };
        try
        {
            mIAsyncControl = CustomProtectedOutputStream.create(outputStream, mUserPolicy,
                    customProtectedOutputStreamCreationCallback);
        }
        catch (InvalidParameterException e)
        {
          …
        }