unresolved reference: openRawResource - reference

I'm trying to use a Trust Manager for Https Connection with a self-signed certificate. Part of my code would consist of loading the certificate from a raw file, but I get the error
Would anybody help me please?
Kotlin plugin version: 1.3.41-release-Studio3.4-1
// Load CAs from an InputStream
val cf: CertificateFactory = CertificateFactory.getInstance("X.509")
val caInput: InputStream = Resources.openRawResource(R.raw.srvca3)
val ca: X509Certificate = caInput.use {
cf.generateCertificate(it) as X509Certificate
}
val keyStoreType = KeyStore.getDefaultType()
val keyStore = KeyStore.getInstance(keyStoreType).apply {
load(null, null)
setCertificateEntry("ca", ca)
}
...
Unresolved reference: openRawResource

Is this Resources the android.content.res.Resources class? Then openRawResource(int) is instance method, not static method there. You need to have some instance (an object) of Resources type to call the method on it. Like:
fun yourFun(resources1: Resources) { // Pass it.
var resources2: Resources = ... // Or create it.
resources1.openRawResource(R.raw.srvca3)
}
Answer like this from this link.
https://discuss.kotlinlang.org/t/resources-openrawresource-unresolved-reference/13689/2
Or
check Is R file path correct :)

Related

Adding .cer file with public key to .NET Core 2 with Sustainsys

I have a .cer file which includes the public key that I need in order to test authentication against AD FS.
I can easily add it in the MVC sample in Web.config (setting signingCertificate fileName) existing in the solution and it seems to work but I can't find any way to add in the AspNetCore2 project.
The closest I've found is the SigningServiceCertificate but that only has a getter and I've read in another thread that it's supposedly to add the public key to the SigningKeys collection somehow, I just can't figure it out how.
Thank you!
I'm not sure exactly what you are asking however I use Sustainsys with a certificate and I use the following line:
var idp = new Sustainsys.Saml2.IdentityProvider(new entityId("https://sso.acme.com"), opt.SPOptions) { ... insert properties ... }
idp.SigningKeys.AddConfiguredKey(new X509Certificate2("customer-certificate.cer"));
opt.SPOptions.ServiceCertificates.Add(EncryptionHelper.GetX509Certificate2("INSERT-THUMBPRINT-OF-YOUR-CERTIFICATE"));
Where EncryptionHelper.GetX509Certificate2 is a custom helper I've written to read my certificate.
Here is the code for EncryptionHelper - I produced it on the back of one of the many examples online.
public static X509Certificate2 GetX509Certificate2(string thumbprint)
{
X509Certificate2 retVal = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates;
var signingCert = certCollection.Find(X509FindType.FindByThumbprint, thumbprint, false);
if (signingCert.Count > 0)
{
retVal = signingCert[0];
}
return retVal;
}
Note that if you are running this in Azure then you also need to add the Thumbprint to Application Settings using these instructions - https://learn.microsoft.com/en-us/azure/app-service/app-service-web-ssl-cert-load
You can find the thumbprint as per these instructions - https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-retrieve-the-thumbprint-of-a-certificate

I get an Amazon.S3.AmazonS3Exception: A provisioning code must be provided Exception When I try to create a new Bucket, AWSSDK 3.1.6 C# AmazonS3

I am trying to connect amazon S3 + cleversafe with C# , I am using AWSSDK 3.1.0.0.
I want to create a new Bucket.
I have a Provisioning Code = "my provisioning code" , host="my host", accesskey="my access key", secretKey="my secret key"
I tried the following code :
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { return true; };
BasicAWSCredentials basicCredentials = new BasicAWSCredentials("my access key", "mysecretkey");
AmazonS3Config configurationClient = new AmazonS3Config();
configurationClient.ForcePathStyle = true;
configurationClient.ServiceURL = "https://###.##.###.###";// my host is IPAdress
configurationClient.UseHttp = false;
try
{
using (AmazonS3Client clientConnection = new AmazonS3Client(basicCredentials, configurationClient))
{
PutBucketRequest newBucket = new PutBucketRequest();
newBucket.UseClientRegion = true;
newBucket.BucketName = "NewBucketCleversafe";
PutBucketResponse response = clientConnection.PutBucket(newBucket);
}
}
catch (AmazonS3Exception exception)
{
}
but I get an "Amazon.S3.AmazonS3Exception: A provisioning code must be provided"
also I tried configurationClient.AuthenticationRegion = "my provisioning code"
Where Can I insert it("my provisioning code") in order to fix this Exception? Which Amazon S3 Class, Amazon S3 property should be modified?
Do you know How Can I fix it? any comment or idea could be help. Thanks for your time.
after a meeting with cleversafe he told me that I have to use BucketRegionName.so I used it but I get another Exception message "XML malformed exception " see more detail about it in https://github.com/aws/aws-sdk-net/issues/396(I do not get additional information about it from AWSSDK .net repository).
So conclusion Probably Cleversafe does not support createbucket using AWSSDK #C 3.1.6 3.5 .net

Azure Schema Extensions in Graph Client

Whatever I tried I cannot set an extension property on a User object, here is a reproducible piece of code:
public async Task CleanTest(string extName)
{
ExtensionProperty ep = new ExtensionProperty
{
Name = extName,
DataType = "String",
TargetObjects = { "User" }
};
App app = (App)(await _client.Applications.Where(a => a.AppId == _managementAppClientId).ExecuteSingleAsync());
app.ExtensionProperties.Add(ep);
await app.UpdateAsync();
GraphUser user = (GraphUser)(await _client.Users.Where(u => u.UserPrincipalName.Equals("email")).ExecuteSingleAsync());
string propName = FormatExtensionPropertyName(extName); //formats properly as extesion_xxx_name
user.SetExtendedProperty(propName, "testvalue");
//user.SetExtendedProperty(extName, "testvalue");
await user.UpdateAsync(); // fails here
}
user.UpdateAsync() according to Fiddler doesn't even go out and application fails with an exception:
"The property 'extension_e206e28ff36244b19bc56c01160b9cf0_UserEEEqdbtgd3ixx2' does not exist on type 'Microsoft.Azure.ActiveDirectory.GraphClient.Internal.User'. Make sure to only use property names that are defined by the type."
This issue is also being tracked here:
https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console/issues/28
I've got an alternative workaround for this bug, for those that want to use the version 5.7 OData libraries rather than redirecting to the v5.6.4 versions.
Add a request pipeline configuration handler.
// initialize in the usual way
ActiveDirectoryClient activeDirectoryClient =
AuthenticationHelper.GetActiveDirectoryClientAsApplication();
// after initialization add a handler to the request pipline configuration.
activeDirectoryClient.Context
.Configurations.RequestPipeline
.OnMessageWriterSettingsCreated(UndeclaredPropertyHandler);
In the handler, change the ODataUndeclaredPropertyBehaviorKinds value on the writer settings to SupportUndeclaredValueProperty.
private static void UndeclaredPropertyHandler(MessageWriterSettingsArgs args)
{
var field = args.Settings.GetType().GetField("settings",
BindingFlags.NonPublic | BindingFlags.Instance);
var settingsObject = field?.GetValue(args.Settings);
var settings = settingsObject as ODataMessageWriterSettings;
if (settings != null)
{
settings.UndeclaredPropertyBehaviorKinds =
ODataUndeclaredPropertyBehaviorKinds.SupportUndeclaredValueProperty;
}
}
Just in case you still looking for solution to this problem or someone else is facing the same issue:
I got similar issue and it looks like, at least for me, the problem was in latest version of "Microsoft.Data.Services.Client" package - 5.7.0 (or in one of it dependencies). When I downgraded to previous version - 5.6.4 it worked as a charm.
I had same symptoms - updating of extended property was failing even w/o any request is made (also used Fiddler)
Hope it helps!
Artem Liman

Connect to a SharePoint site when IIS requires client certificates

I currently have an application developed in C# that helps me in managing permissions on our Share-point 2013 site. Recently, I learned we may be loosing our local instance and moving to another instance that's behind a cac enforced IIS. I have converted one of my test sites to require certificates and have tried several way to send the cert to the IIS server but I still get
"The remote server returned and error: (403) Forbidden.
Below is a few things I have tried.
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.ClientCertificates.Add(pki.GetClientCertificate());
handler.UseProxy = false;
using (var client = new HttpClient(handler))
{
context connection code here
}
the pki.GetClientCertificate is a method, I made that returns a selected certificate in this case my cac cert. Its funny that SharePoint designer connects without issue or prompt. Any help on this matter would be much appreciated.
Just to add some more things I have tried
context.Credentials = new SharePointOnlineCredentials(uli.username, uli.password);
the uli username is the certificate converted to username I have a class that dose the conversion. the password is the pin converted to a secure string. I get the same message even when adding the credentials to the context.
I found a workable but slow solution here:
http://sharepoint.findincity.net/view/635399286724222582121618/ssl-certificate-error-when-using-client-object-model
The only issue with this is every time I call the context I have to send the certificate chain. One thing I changed from this users code is the following.
static void context_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
IntPtr ptr = IntPtr.Zero;
X509Certificate2 certificate = null;
X509Certificate t = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
// Nothing to do if no cert found.
HttpWebRequest webReq = e.WebRequestExecutor.WebRequest;
//webReq.Proxy = new WebProxy("http://[ProxyAddress]");
//Specify a proxy address if you need to
// X509Certificate cert = pki.GetClientCertificate();
foreach (X509Certificate c in store.Certificates)
{
webReq.ClientCertificates.Add(c);
}
}
I just dumped all my certificates into the request because I didn't want to have a prompt every time I clicked something. So if anyone has a more efficient way to do this let me know.
The code below shows the use of the clientcontext and how it validates your cert
using (context = new ClientContext(siteurl))
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
return validationResult;
};
context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);
//add all your context commands below this line
}

Jetty SSL server

Following is my code for the secure ssl server. I have created a keystore "server" and it has the key pair generated with passwords.
public static void main(String[] args) throws Exception {
Server server = new Server();
HttpConfiguration https_config = new HttpConfiguration();
https_config.setSecureScheme("https");
https_config.setSecurePort(8443);
https_config.addCustomizer(new SecureRequestCustomizer());
https_config.setSendServerVersion(true);
File keystoreFile = new File("server");
System.out.print(keystoreFile.getAbsolutePath());
SslContextFactory sslContextFactory = new SslContextFactory();
if (keystoreFile.exists())
{
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setTrustStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("secret");
sslContextFactory.setKeyManagerPassword("secret");
sslContextFactory.setTrustStorePassword("secret");
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
}
ServerConnector https =
new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
https.setPort(8443);
server.setConnectors(new Connector[] { https});
ServletContextHandler scHandler = new ServletContextHandler(server,"/");
scHandler.addServlet(Testpage1.class, "/test");
server.setHandler(scHandler);
server.start();
}
}
when I tried to connect to using the https://localhost:8443/ or https://localhost:8443/test it gives me "web page not available error" and with curl it gives me "curl: (35) Unknown SSL protocol error in connection to localhost:8443"
Could some one guide me to debug this issue.
I decided to post the question after a full day of debugging and trials and but with a little suggestion from a friend I manage to solve the issue by updating the keystore. So the issue I was having was due to the keys I have generated int he key store. It seems you need to use RSA algorithm not the EC algorithm.

Resources