In android api 22 I can use only this function to create keys and certificate:
Calendar notBefore = Calendar.getInstance();
Calendar notAfter = Calendar.getInstance();
notAfter.add(Calendar.YEAR, 2);
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getApplicationContext())
.setAlias(KEY_ALIAS_CSR)
.setKeySize(2048)
.setSubject(new X500Principal(
"CN=Your Company ," +
" O=Your Organization" +
" C=Your Coountry"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(notBefore.getTime())
.setEndDate(notAfter.getTime())
.build();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
generator.initialize(spec);
generator.generateKeyPair();
I there possibility to set Purpose_Sign of this certificate?
In Api > 23 is easy:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.build());
Solved!
String principal = String.format(CN_PATTERN, cn);
ContentSigner signer = new JCESigner((PrivateKey) keyStore.getKey(KEY_ALIAS_TLS, null), DEFAULT_SIGNATURE_ALGORITHM);
PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
new X500Name(principal), keyStore.getCertificate(KEY_ALIAS_TLS).getPublicKey());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
**extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(
true));
extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(
KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment
));
extensionsGenerator.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));**
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
extensionsGenerator.generate());
PKCS10CertificationRequest csr = csrBuilder.build(signer);
Related
Good day All,
I am using ComponentSpace as a Service Provider to establish SAML2 Single Sign On to my for my clients. The clients use their own identity providers to authenticate and gain access to my MVC5 web application. The issue I am having is that when a client wants to update their X509 certificate files I update the physical files dynamically, but I have to do an IIS reset to get the new certificate files to be used. How can I avoid having to do an IIS reset and get ComponentSpace to use the new X509 certificate files when authenticating. An example of my code is below.
var samlConfiguration = new
ComponentSpace.SAML2.Configuration.SAMLConfiguration();
var ssoUrl = "https://www.ssoUrl/Consumer";
var ssoName ="https://www.ssoName";
var localServiceProviderConfiguration = new LocalServiceProviderConfiguration()
{
Name = ssoName,
AssertionConsumerServiceUrl = ssoUrl
};
samlConfiguration.LocalServiceProviderConfiguration = localServiceProviderConfiguration ;
var certNamePrimary = ConfigurationManager.AppSettings["Certificate_Path"] + "cert-A.cer";
var certNameSecondary = ConfigurationManager.AppSettings["Certificate_Path"] + "cert-B.cer";
var partnerIdentityProviderConfiguration = new
ComponentSpace.SAML2.Configuration.PartnerIdentityProviderConfiguration()
{
Name = clientConfig.PartnerIdPName,
SingleSignOnServiceUrl = clientConfig.IdPSingleSignOnServiceURL,
SignAuthnRequest = false,
WantSAMLResponseSigned = false,
WantAssertionEncrypted = false,
WantAssertionSigned = true,
PartnerCertificateFile = certNamePrimary ,
SecondaryPartnerCertificateFile = certNameSecondary
};
samlConfiguration.PartnerIdentityProviderConfigurations.AddPartnerIdentityProvider(partnerIdentityProviderConfiguration );
if (ComponentSpace.SAML2.SAMLController.Configurations.Keys.Contains(ssoUrl))
{
ComponentSpace.SAML2.SAMLController.Configurations.Remove(ssoUrl);
ComponentSpace.SAML2.SAMLController.Configurations.Add(ssoUrl, samlConfiguration);
}
else
ComponentSpace.SAML2.SAMLController.Configurations.Add(ssoUrl, samlConfiguration);
ComponentSpace.SAML2.SAMLController.ConfigurationID = ssoUrl;
SAMLServiceProvider.InitiateSSO(Response, null, "http://company.com/adfs/services/trust");
I am connecting to Gemalto HSM which supports secp256r1. I have the following code to create an ECDSA key pair using Pkcs11interop. I am getting the paramsBytes using BouncyCastle NistNamedCurves and X962Parameters.
The HSM keeps comming back with CKR_ATTRIBUTE_TYPE_INVALID. I am new to ECDSA so I may have missed something. Any ideas?
X9ECParameters x9Ec = NistNamedCurves.GetByName("P-256");
X962Parameters x962 = new X962Parameters(x9Ec);
byte[] paramsBytes = x962.GetDerEncoded();
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = session.GenerateRandom(20);
// Prepare attribute template of new public key
List<ObjectAttribute> publicKeyAttributes = new List<ObjectAttribute>();
publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, keyName));
publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ECDSA_PARAMS, paramsBytes));
// Prepare attribute template of new private key
List<ObjectAttribute> privateKeyAttributes = new List<ObjectAttribute>();
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, keyName));
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ECDSA_PARAMS, paramsBytes));
// Generate key pair
Mechanism mechanism = new Mechanism(CKM.CKM_ECDSA_KEY_PAIR_GEN);
ObjectHandle publicKeyHandle = null;
ObjectHandle privateKeyHandle = null;
session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle,
out privateKeyHandle);
Found out what was going on. The HSM did not like the
privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ECDSA_PARAMS, paramsBytes));
on the private key. PKCS states that the ECDSA params need to be on the public key and can't be on the private key and this implementation enforced that.
In CKA_ECDSA_PARAMS you can insert a byte[] which is specific for any curve name. a list of available names and related byte[] are presented here at SSL GitHub project.
Another thing, add (CKA.TOKEN, true) as other attributes for private key.
I keep getting a 401 when I try to add a customer with QB Online API v3. The xml works in the API Explorer, and I'm able to query customers from my program. I just can't POST. What am I doing wrong?
string reqBody = "<Customer xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\"><DisplayName>Empire Records</DisplayName>"
+ "<BillAddr><Line1>201 S King St</Line1><City>Seattle</City><CountrySubDivisionCode>WA</CountrySubDivisionCode><PostalCode>98104</PostalCode></BillAddr>"
+ "<PrimaryPhone><FreeFormNumber>425-867-5309</FreeFormNumber></PrimaryPhone><PrimaryEmailAddr><Address>helpme#thefly.con</Address></PrimaryEmailAddr></Customer>";
IConsumerRequest req = session.Request();
req = req.Post().WithRawContentType("application/xml").WithRawContent(System.Text.Encoding.ASCII.GetBytes(reqBody));
req.AcceptsType = "application/xml";
string response = req.Post().ForUrl("https://quickbooks.api.intuit.com/v3/company/" + realmID + "/customer").ToString()
OAuthConsumerContext consumerContext1 = new OAuthConsumerContext
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
};
OAuthSession oSession1 = new OAuthSession(consumerContext1, "https://oauth.intuit.com/oauth/v1/get_request_token",
"https://workplace.intuit.com/Connect/Begin",
"https://oauth.intuit.com/oauth/v1/get_access_token");
oSession1.ConsumerContext.UseHeaderForOAuthParameters = true;
I need a Form authentication over 3 Sites (login.mydomain.com, www.mydomain.com and admin.mydomain.com). Users are from a MSSQL-DB, but I don't think that's a problem.
I've set up my web.config as described here: http://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx , but it doesn't work.
My code for the login:
string RoleString = string.Empty;
RoleString = user.Gruppe.Bezeichnung;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(2), false, user.Gruppe.name, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Name = "UserCookie";
cookie.Domain = ".mydomain.com";
Response.Cookies.Add(cookie);
Response.Redirect("http://www.mydomain.com/Default.aspx");
What could be the problem? I tried with machine key in webconfig, but that gave me an error with the Viewstate of the MAC...
This is the Login Info Method
private void SetLogonInfo()
{
try
{
LogInfo.ConnectionInfo.ServerName = "ServerName";
LogInfo.ConnectionInfo.UserID = "UserID";
LogInfo.ConnectionInfo.Password = "Password";
LogInfo.ConnectionInfo.DatabaseName = "DataBase";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To create report I used this code
crystalReportViewer1.ReportSource = null;
rptdoc = new ReportDocument();
rptdoc.Load("REPORTS\\TC.rpt");
crystalReportViewer1.SelectionFormula =selectionFormula;
crystalReportViewer1.ReportSource = rptdoc;
rptdoc.Database.Tables[0].ApplyLogOnInfo(LogInfo);
It works well in server system, but if I use this in client systems, it asks for username and password. I'm using Crystal Reports 10. Moreover sometimes it asks for Username password in server system also. How to resolve this?
You're doing things in the wrong order. You need to do the login programmatically BEFORE you load the report on the viewer.
Additionally, I cannot stress enough that you need to test your program on the server machine and a test client machine before you release it to users.
The reason for this error is wrong username, password.
Check username, password and use the code below:
ReportDocument cryRpt = new ReportDocument();
TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
ConnectionInfo crConnectionInfo = new ConnectionInfo();
Tables CrTables;
//This is for Access Database
crConnectionInfo.ServerName = "" + "" +Application.StartupPath + "\\Database.mdb"; //access Db Path
crConnectionInfo.DatabaseName = "" + "" + Application.StartupPath + "\\Database.mdb";//access Db Path
crConnectionInfo.UserID = "ADMIN";
crConnectionInfo.Password = Program.DBPassword; //access password
//This is for Sql Server
crConnectionInfo.UserID = Program.Severuser; //username
crConnectionInfo.Password = Program.Password;//password
crConnectionInfo.ServerName = Program.server;//servername
crConnectionInfo.DatabaseName = Program.database;//database
string path = "" + Application.StartupPath + "\\supportingfiles\\Invoice.rpt";
cryRpt.Load(path);
CrTables = cryRpt.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
{
crtableLogoninfo = CrTable.LogOnInfo;
crtableLogoninfo.ConnectionInfo = crConnectionInfo;
CrTable.ApplyLogOnInfo(crtableLogoninfo);
}
cryRpt.SetParameterValue("invoiceno", Program.billno);
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();