I have to decode an XML encrypted document. The relevant part is:
<Master_key>
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
<KeyInfo>
<ds:KeyName>TK</ds:KeyName>
<ds:RetrievalMethod URI="#TK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey" />
</KeyInfo>
<CipherData>
<xenc:CipherValue>73CEFD0CE530C157C275152964EFBC322D26C2E356A3F3079E026FB2B6B562BD810043066300924078472229583118A8</xenc:CipherValue>
<xenc:FingerPrint>739E0E8490EACBCB2EA11D4A5DBEFBAE888B092E</xenc:FingerPrint>
</CipherData>
</Master_key>
The Master_Key is an encrypted element. aes256-cbc is used for encryption. The AES256 key is a session key and defined at the begin of the XML:
<Security>
<Transport_key Id="TK">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo>
<ds:RetrievalMethod URI="#PKC" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey" />
</KeyInfo>
<CipherData>
<xenc:CipherValue>968A0AFA54DAD4081FC264C90CD5F1341AD8274F130F5E9E8DC397B9FE3B7EC00FC72DD8C8A22B6E8A606B7693B80882777972D61316FD280A64D166DD0DA08748D285A2D4236DC92153C7A3ECF77580F380BE1A4E8B5E688BDB090A92B5C0CF3C1D90E00E73B4B50940195587DECB1ECF686B51C3C566D0BC36EA5EC0E87C32827EFFCDD3B5A91AF9AD0A0594527E43395CB6CC44653F60F9792505598709FE2C5F1BD21BAA8B6C9C02ADE354B7E8717BE999A11B6422F6C67B0D7A13C96051658C2B0315812DD772321E9820FEE73843C76869F65FE6327253A5BDD1255EF4DEA9B5A17DB54A5B7AEEA1DB4BEA018301E2CAB04B79A3EF81A419DB2B837404</xenc:CipherValue>
<xenc:FingerPrint>1F1862AFB4CC212C18439F12C1C3E6B615E70F65</xenc:FingerPrint>
</CipherData>
<CarriedKeyName>TK</CarriedKeyName>
</Transport_key>
</Security>
It is itself encrypted with rsa-1_5, based on a public key, for which the decrypter must have the private key.
I have to decrypt the content. Although I know the private key, I have no idea at the moment how to do that. In particular I'm wondering why the ciphered value
73CEFD0CE530C157C275152964EFBC322D26C2E356A3F3079E026FB2B6B562BD810043066300924078472229583118A8
is 48 Bytes long. Shouldn't it be a multiple of 32 Bytes, because AES256 uses a blocklength of 256bits=32bytes.
I would appreciate any help...
Related
I have followed the Microsoft documentation to encrypt the Assertions, but it gives me some error.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/connect-with-saml-service-providers#enable-encrypted-assertions-optional
MetaData:
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://samltestapp2.azurewebsites.net">
<SPSSODescriptor AuthnRequestsSigned="true" WantAssertionsSigned="true" protocolSupportEnumeration=" urn:oasis:names:tc:SAML:2.0:protocol">
<NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</NameIDFormat>
<AssertionConsumerService index="0" isDefault="true" Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://samltestapp2.azurewebsites.net/SP/AssertionConsumer"/>
<KeyDescriptor use="encryption">
<KeyInfo xmlns="https://www.w3.org/2000/09/xmldsig#">
<X509Data>
<X509Certificate>MIIDODCCAiCgAwIBAgIQEaP5fKYAQ6VBxbBPDi/IVDANBgkqhkiG9w0BAQsFADAv MS0wKwYDVQQDDCRlbmNyeXB0aW9uLm9kZmxkZW1vNS5vbm1pY3Jvc29mdC5jb20w HhcNMjEwMTE5MDQ0NDQzWhcNMjIwMTE5MDQ1NDQzWjAvMS0wKwYDVQQDDCRlbmNy eXB0aW9uLm9kZmxkZW1vNS5vbm1pY3Jvc29mdC5jb20wggEiMA0GCSqGSIb3DQEB AQUAA4IBDwAwggEKAoIBAQClIee7OMFzTsZ3eDdTpDJOB0qsZCiGug3DtOoBrZsY pG6SNI1z7hPWiMJBJWaGrSPF/FcKS/RaOZi+G/Ht7RR+4qTzY2toqD7R7HYL8fyg lNx9d0n2RDRlgIHo9vtopw9fZaiEsvY3DiWWed9EvhQPyn9ewiZBWDLIlyOFT6oo jTiz6/xMneI96l8A7IQ+TAQbH2oUTaDTHksehmeVk3ExeWvgmfTzE812kzRMmWeP awlLJrCtRUu+NvxfDcmbv7bzxRfyDmM8gw7MIqELkIG4rNfFn0VvDnA7+oECm2DQ LKZgJZkAHJ+UWbKGj39CqOy6vkjA20pPtlhob5hp2qv1AgMBAAGjUDBOMA4GA1Ud DwEB/wQEAwIHgDAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwEwHQYDVR0O BBYEFC1rpD8SwvSUXRvLJY072Vtf21LfMA0GCSqGSIb3DQEBCwUAA4IBAQBmD7MU vVXyX7nZ3h1rvhQUI4ryd3DUNdWZA2frdPm8xx6WQfEJKlYLKsRErcaCFXc9CGFK 2Ijfb9D0NxYo9JNJd9c2j2sDgZyxud5zn9xmSb3VZ42E+9y8NQz+UCYl6xlRIwwh vIdRpsVhmcXjcpW9Sos2kZ5wOnnROp6VwYTKSVDJyJYXPEz8is7Hhv5a7gsDW2pO GQAZXKxuH10IIpudxBszdwRGt3O945hyGsJNySljvvwoPiBwtZbSQbjpzmMGkFU9 BetAjN25+kSa8CNjv2wbLbs4boY/SmVTxMDHQpZ6k9fdms2Rdidl0o6BKKtjdkeE fH/F9XGJ2EbQKNwD</X509Certificate>
</X509Data>
</KeyInfo>
</KeyDescriptor>
</SPSSODescriptor>
</EntityDescriptor>
Relying party file:
<RelyingParty>
<DefaultUserJourney ReferenceId="SignUpOrSignInSAML" />
<UserJourneyBehaviors>
<JourneyInsights TelemetryEngine="ApplicationInsights" InstrumentationKey="xxxxxxxxxxxxxx" DeveloperMode="true" ClientEnabled="false" ServerEnabled="true" TelemetryVersion="1.0.0" />
<ScriptExecution>Allow</ScriptExecution>
</UserJourneyBehaviors>
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="SAML2"/>
<Metadata>
<Item Key="PartnerEntity">{Settings:MetadataURL}</Item>
<Item Key="ResponsesSigned">false</Item>
<Item Key="WantsEncryptedAssertions">true</Item>
<Item Key="IdpInitiatedProfileEnabled">true</Item>
</Metadata>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="givenName" />
<OutputClaim ClaimTypeReferenceId="surname" PartnerClaimType="surname" />
<OutputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="sub"/>
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
Saml2AssertionIssuer:
<TechnicalProfile Id="Saml2AssertionIssuer">
<DisplayName>Token Issuer</DisplayName>
<Protocol Name="SAML2"/>
<OutputTokenFormat>SAML2</OutputTokenFormat>
<Metadata>
<!-- The issuer contains the policy name; it should be the same name as configured in the relying party application. B2C_1A_signup_signin_SAML is used below. -->
<Item Key="IssuerUri">{Settings:SignupSignInSAMLIssuerURI}</Item>
</Metadata>
<CryptographicKeys>
<Key Id="MetadataSigning" StorageReferenceId="B2C_1A_SamlIdpCert"/>
<Key Id="SamlAssertionSigning" StorageReferenceId="B2C_1A_SamlIdpCert"/>
<Key Id="SamlMessageSigning" StorageReferenceId="B2C_1A_SamlIdpCert"/>
<Key Id="SamlAssertionDecryption" StorageReferenceId="B2C_1A_SamlIdpCertEnc"/>
</CryptographicKeys>
<InputClaims/>
<OutputClaims/>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-Saml-issuer"/>
</TechnicalProfile>
I am getting the below error. It is working properly without encryption, but if I enable the encryption getting that issue. Can someone suggest me a way to resolve this error.
Thanks #Saravana. WantsSignedAssertion indicates whether the technical profile requires all incoming assertions to be signed and SAML Response Assertion elements received by the relying party application must be signed. B2C requires both, the message and the assertion to be signed. If only assertion is signed, then it fails, and B2C does not accept it.
Please verify with the SAML decoder tool and see if both the assertion and the message are signed or not.
Please let us know if you need more help.
Reference:- https://github.com/azure-ad-b2c/saml-sp/blob/master/saml-rp-spec.md
I have SAML Response and Metadata URL provided by Client (Identity Provider). How I (Service Provider) Can decrypt the SAML Response
Below is the SAML Response
<samlp:Response ID="_17222aef-2970-44d1-aae6-1c25187c4319" Version="2.0" IssueInstant="2017-06-29T10:23:12.036Z" Destination="https://ssotest-1246771484.ap-south-1.elb.amazonaws.com/ssotest/index.html" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
InResponseTo="a351b3fi19a2024838868e374da59j6" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://yyy.xxx.com/adfs/zzz/trust</Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
<EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
<xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
</e:EncryptionMethod>
<KeyInfo>
<ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:X509IssuerSerial>
<ds:X509IssuerName>CN=apollo, OU=R&D, O=RM5 Software Oy, L=Helsinki, S=Uusimaa, C=FI</ds:X509IssuerName>
<ds:X509SerialNumber>1357039681</ds:X509SerialNumber>
</ds:X509IssuerSerial>
</ds:X509Data>
</KeyInfo>
<e:CipherData>
<e:CipherValue>f6yX7d1FF4eHtj79WRxJ/xga3qhUASk79sTHWDfKW/bHbIGL+UVwBIdQIh21AMbLN/1cgiVCps7UBAoaipew7JQCq1EYQR/ipFO7Wcmoqs5V1h/KwBgNdhT/L/TqAacIz9QoRPkNhxsDAKMvd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1ukp+vO4A2RW5Kjbpei611sjgZ7CJKjj2Wbz6cRj8D4ahlpLAm6ybhxNTxipLNSBOU7SMl9MltDPZ3lzQHssW2vThYLeKXezJ7JSwlAKC1u4x9GwpoQiZsqoQoMqHqzcgGYKNfyktp8sRrtsIBXhnq7hX2eiwDXTFCjQGqvdC8topw1vGrtGU9HsYgdyZR0iVo2lJ+Cifp7JtaDE6mYYkqMUtn2REubl6hpaLnfRzlRv2GTCBGXz04Z/TbY9llhHVpOMsdbD6WpIBH4euFA3No5EplHlaG54bjrpOYWr6A5xx5GU26wvlu7JlAV+YrXfmAFmsocbjTiiM45ah</xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
How encryption scenario works in SAML: identity provider encrypts some elements of the SAML response with service provider's public key. The service provider decrypts using the private key that corresponds to the public key used to encrypt. In other words, the service provider needs to own a keypair - private key and public key - for this use case to work.
Assuming you have the private key for decryption, you just need to decide on the implementation approach. Rolling your own is technically possible but unlikely to succeed. For .NET we recommend either Sustainsys or ITFoxtec, both are OSS and support decryption.
I'm trying to decrypt a Web.config section that was encrypted with RSA from an external Powershell script. The section goes:
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>.......</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>.......</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
The code goes:
[xml]$x = Get-Content "$Path\Web.config"
$Prov = New-Object System.Configuration.RsaProtectedConfigurationProvider
$Prov.Decrypt($x.configuration.connectionStrings.EncryptedData)
It's executed via remote Powershell on the server where the config is. The account is an admin, so local machine keys should be available. And I'm getting an error:
Value cannot be null. Parameter name: keyName
An identical, modulo provider name, fragment works for DPAPI encrypted sections. The key name is right there in the section. What am I missing here?
Update: when the Web code does it, it calls Initialize() on the provider first. I've mimicked the parameters on that Initialize call. They come from machine. config.
$nv = New-Object System.Collections.Specialized.NameValueCollection
$nv.Add("description", "Uses RsaCryptoServiceProvider to encrypt and decrypt")
$nv.Add("keyContainerName", "NetFrameworkConfigurationKey")
$nv.Add("cspProviderName", "")
$nv.Add("useMachineContainer", "true")
$nv.Add("useOAEP", "false")
$Prov.Initialize("RsaProtectedConfigurationProvider", $nv)
Now I'm getting a different error: "Bad data".
Update 2: tried siccing aspnet_regiis on that file, got the same "Bad data" error. But the site itself seems up and running and database aware. Maybe the connectionString section is damaged after all, and the site takes it elsewhere.
I"m not sure about doing it via Powershell but here's what I do manually via code-behind on a web page. There might be a clue in here. I can delete this answer if it doesn't help.
protected void btnEncryptConnStrings_Click(object sender, EventArgs e)
{
// Open web.config file as a configuration object to get information.
Configuration objConfigFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Work with the <connectionStrings> section.
ConfigurationSection connectionStrings = objConfigFile.GetSection("connectionStrings");
if(connectionStrings != null)
{
// Only encrypt the section if it is not already protected.
if(!connectionStrings.SectionInformation.IsProtected)
{
// Encrypt the <connectionStrings> section using the
// DataProtectionConfigurationProvider provider (see notes at top of file).
connectionStrings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); // alt: DataProtectionConfigurationProvider
objConfigFile.Save();
// other stuff.
}
}
}
This is the service callout policy:
<ServiceCallout name="GeoCodeClient">
<Request clearPayload="false" variable="GeocodingRequest" />
<Response>GeocodingResponse</Response>
<Timeout>30000</Timeout>
<HTTPTargetConnection>
<URL>http://maps.googleapis.com/maps/api/geocode/json</URL>
</HTTPTargetConnection>
</ServiceCallout>
Let us say I have to access a resource that is username/password protected. How do I add that basic authorization to this policy to enable me to do that?
In our project a KeyValueMaps are used to store the basic auth info at org level. The authorisation information is retrieved using the KeyValueMap policy and added as the basic auth header to the request message.
See if this approach works for you.
To add Basic Authentication header for your service callout, you can use an 'AssignMessage' policy that sets the 'Authorization' header in the 'GeocodingRequest' as follows:
<AssignMessage enabled="true" continueOnError="true" async="false" name="AssignAuthorizationHeaderPolicy">
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="true" transport="http" type="request">GeocodingRequest</AssignTo>
<Add>
<Headers>
<Header name="Authorization">Basic YourAuthenticationHeader</Header>
</Headers>
</Add>
</AssignMessage>
Once you have created this policy, you will need to attach it in the request flow before the serviceCallout in the proxy.xml as flows:
<Step>
<FaultRules/>
<Name>AssignAuthorizationHeaderPolicy</Name>
</Step>
<Step>
<FaultRules/>
<Name>GeoCodeClient</Name>
</Step>
to add to what's already been said, if you need base64 encoding (and you probably will if you're using Basic Authorization), you'll need to do script callout. For instance, you can use the following Python:
import base64
if (client_secret is not None):
data = client_id + ":" + client_secret
header_value = base64.b64encode(data)
header_value = "Basic " + header_value
flow.setVariable("request.header.Authorization", header_value)
JS will be a little trickier since you need to include appropriate libraries, but I'm sure SO has plenty of more examples to follow for that.
Using Key Value Map to store sensitive data in a secure way
Step 1)Use below API to Create/Update the key Value maphttps://api.enterprise.apigee.com/v1/o/{orgname}/environments/{env}/keyvaluemaps Body:-{
"entry" : [ {
"name" : "basic_auth_system1",
"value" : "Basic XXXXXXXXXXX"
} ],
"name" : "system1_credentials"
}
Step 2) Policy used to lookup The key Value map
<KeyValueMapOperations enabled="true" continueOnError="false" async="false" name="keymap_get_credentials" mapIdentifier="system1_credentials">
<DisplayName>keymap_get_credentials</DisplayName>
<FaultRules/>
<Properties/>
<ExpiryTimeInSecs>-1</ExpiryTimeInSecs>
<Get assignTo="basic_auth_system1">
<Key>
<Parameter>basic_auth_system1</Parameter>
</Key>
</Get>
<Scope>environment</Scope>
</KeyValueMapOperations>
How can I encrypt only passwords in a web.config file?
<add name="PSystem" connectionString="Server=test;Database=Dev;User ID=testuser;Password=password#123;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />
I believe that built-in encryption mechanisms work on the entire connectionString section:
See this website for more info
If you would like to encrypt in-memory passwords, maybe entered by the user through a login form, you could use SecureString
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
To encrypt configuration file
contents, use the Aspnet_regiis.exe tool with the –pe option and the
name of the configuration element to be encrypted.
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov
"RsaProtectedConfigurationProvider"
Source: http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx