WrappedKeySecurityToken CreateWrappedKeyToken(string id, string encryptionMethod, string carriedKeyName, SecurityKeyIdentifier unwrappingTokenIdentifier, byte[] wrappedKey, SecurityTokenResolver tokenResolver) { ISspiNegotiationInfo sspiResolver = tokenResolver as ISspiNegotiationInfo; if (sspiResolver != null) { ISspiNegotiation unwrappingSspiContext = sspiResolver.SspiNegotiation; // ensure that the encryption algorithm is compatible if (encryptionMethod != unwrappingSspiContext.KeyEncryptionAlgorithm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.BadKeyEncryptionAlgorithm, encryptionMethod))); } byte[] unwrappedKey = unwrappingSspiContext.Decrypt(wrappedKey); return(new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingSspiContext, unwrappedKey)); } else { if (tokenResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("tokenResolver")); } if (unwrappingTokenIdentifier == null || unwrappingTokenIdentifier.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.MissingKeyInfoInEncryptedKey))); } SecurityToken unwrappingToken; SecurityHeaderTokenResolver resolver = tokenResolver as SecurityHeaderTokenResolver; if (resolver != null) { unwrappingToken = resolver.ExpectedWrapper; if (unwrappingToken != null) { if (!resolver.CheckExternalWrapperMatch(unwrappingTokenIdentifier)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken, unwrappingToken))); } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, resolver))); } } else { try { unwrappingToken = tokenResolver.ResolveToken(unwrappingTokenIdentifier); } catch (Exception exception) { if (exception is MessageSecurityException) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException( SR.GetString(SR.UnableToResolveKeyInfoForUnwrappingToken, unwrappingTokenIdentifier, tokenResolver), exception)); } } SecurityKey unwrappingSecurityKey; byte[] unwrappedKey = SecurityUtils.DecryptKey(unwrappingToken, encryptionMethod, wrappedKey, out unwrappingSecurityKey); return(new WrappedKeySecurityToken(id, unwrappedKey, encryptionMethod, unwrappingToken, unwrappingTokenIdentifier, wrappedKey, unwrappingSecurityKey)); } }