SHA-384/PSS Signature verification using PointyCastle in Dart - dart

I have a public key, a message and a signature. I want to verify that the signature is correct using SHA-384/PSS signer from PointyCastle.
I managed to build something but the signature verification fails and I suppose it is because of salt parameter which I don't know how to build/create it.
var rsaPublicKey = RSAPublicKey.fromPEM(publicKey);
final signer = Signer('SHA-384/PSS');
AsymmetricKeyParameter<RSAAsymmetricKey> keyParams =
PublicKeyParameter<RSAPublicKey>(rsaPublicKey.asPointyCastle);
signer.init(
false,
ParametersWithSalt(keyParams, Uint8List()), // THIS is the salt
);
final sig = PSSSignature(base64Decode(signature));
final verified = signer.verifySignature(
Uint8List.fromList(message.codeUnits),
sig,
);
I'm not sure what to pass to the second parameter of ParametersWithSalt(keyParams, Uint8List() needed to initialise the signer.
Any hint is highly appreciated.

Related

how to get issue type name by issue type id in SIL script? (besides of of SQL request to DB)

I use createIssue() routine in my script. This routine gnneeds the issue type name as an input.
To make the script resistant to issue type renaming I'd like to put issue type id instaead of issue type name in it. I know how to find out the id, but do do not the convinient way to transform it to name
just wrote a SIL routine, getting issue type name from Jira REST API
function getIssueTypeNameById(int issueID) {
string uname = "username";
string pwd = "password";
HttpRequest request;
HttpHeader header1 = httpBasicAuthHeader(uname, pwd);
request.headers += header1;
string url = "https://<domain>/rest/api/2/issuetype/" + issueID;
struct issueName { string name; }
issueName issName = httpGet(url, request);
return issName;
}

Google Tink: How to get raw key string from a KeysetHandle?

I am new to Tink and would like to extract the raw key data(in String form) from KeysetHandle which I generated like this:
keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.AES128_GCM);
Or maybe some other API to get it.
How can I achieve this?
You can write the Keyset to disk with either KeysetHandle.write(), which requires encryption, other CleartextKeysetHandle.write(). Both require a BinaryKeysetWriter or JsonKeysetWriter.
Example will help. Here is how you would use CleartextKeysetHandle.write() to observe the key profile:
Try this for display:
// display key [Caveat: ONLY for observation]
public void display_key_profile_for_test_observation_only(KeysetHandle keysetHandle) throws IOException, GeneralSecurityException
{
System.out.println("\nDisplay key:");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CleartextKeysetHandle.write(keysetHandle, JsonKeysetWriter.withOutputStream(outputStream));
System.out.println("\n"+ new String(outputStream.toByteArray()));
}
As this belongs to a class, you may have to do some slight code modification. You see the keyword this denoting that the code snippets come from a class. Here is the test usage:
public void trial_usage_key_generation() throws IOException, GeneralSecurityException {
for (CIPHER_SYMMETRIC_ALGOS algo_type : CIPHER_SYMMETRIC_ALGOS.values()) {
System.out.println("Generating key for : " + algo_type);
KeysetHandle keysetHandle = this.generate_key_for_test_observation_only(algo_type);
this.display_key_profile_for_test_observation_only(keysetHandle);
}
}
You can use reflection to get the keyset as code below, or JsonKeysetWriter to get base64ed key bytestring (still needs to be unserialized to corresponding key object to get the raw key bytes).
KeysetHandle keysetHandle = KeysetHandle.generateNew(
AeadKeyTemplates.CHACHA20_POLY1305);
Method method = keysetHandle.getClass().getDeclaredMethod("getKeyset");
method.setAccessible(true);
Keyset keyset = (Keyset) method.invoke(keysetHandle);
ChaCha20Poly1305Key key = ChaCha20Poly1305Key.parseFrom(keyset.getKey(0).getKeyData().getValue());
byte[] keyBytes = key.getKeyValue().toByteArray();

How Createx509certificate2 given certificate bytes and private key - dnx50

Basically i am using a LetsEncrypt service to get a certificate byte[] back that i can turn into a X509Certificate2 but then it is missing the private key to then use it on a SSLStream. I have the private key as a RSAParameters but can also convert it to a byte[] but i can't seem to find a way to get the 2 together in the same X509Certificate2 so i can use it for AuthenticateAsServer on a SSLStream. The methods you would use for dotnet 4 don't seems to apply for dnx50 as far as i can tell. I working example would be perfect and i want to keep the solution in dnx50 as i want to deploy this to linux and windows boxes.
Basically trying to do something similar to Convert Certificate and Private Key to .PFX programatically in C# but to just create the X509 with private key though saving would be my next task.
From what i can tell so far i think that dnx50 does not allow you to create a cetificate object and to then add a private key to it like dotnet 4 did. Instead i think i need to pass in a a file or byte[] that contains both for this to work but i don't know how to merge my 2 byte arrays together or to format them.
Finally worked out a solution for this. Not ideal but it works. Basically it uses bouncyCastle to create a pfx stream and then you can read that in to load the private key with the certificate. To do that on CoreCLR i used the nuget package Portable.BouncyCastle:1.8.1 with the following code i put in a helper class.
public X509Certificate2 CreateX509Certificate2(RSAParameters keys, byte[] certificateBytes, string friendlyName)
{
if (string.IsNullOrWhiteSpace(friendlyName))
{
friendlyName = "default";
}
var store = new Pkcs12Store();
var convertedKeys = GetRsaKeyPair(keys);
var certificate = new X509CertificateParser().ReadCertificate(certificateBytes);
store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(convertedKeys.Private), new X509CertificateEntry[] { new X509CertificateEntry(certificate)});
using (MemoryStream ms = new MemoryStream())
{
var random = new SecureRandom();
string password = random.Next().ToString() + random.Next().ToString() + random.Next().ToString();
store.Save(ms, password.ToCharArray(), random);
var cert = new X509Certificate2(ms.ToArray(), password, X509KeyStorageFlags.Exportable);
return cert;
}
}
private AsymmetricCipherKeyPair GetRsaKeyPair(
RSAParameters rp)
{
BigInteger modulus = new BigInteger(1, rp.Modulus);
BigInteger pubExp = new BigInteger(1, rp.Exponent);
RsaKeyParameters pubKey = new RsaKeyParameters(
false,
modulus,
pubExp);
RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
modulus,
pubExp,
new BigInteger(1, rp.D),
new BigInteger(1, rp.P),
new BigInteger(1, rp.Q),
new BigInteger(1, rp.DP),
new BigInteger(1, rp.DQ),
new BigInteger(1, rp.InverseQ));
return new AsymmetricCipherKeyPair(pubKey, privKey);
}

How can i decrypt the xml file in iOS with AES/CBC/PKCS5Padding standard,in android the file has been decrypted ,all keys like salt, IV

private static Cipher getCipher(int mode) throws Exception {
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
//a random Init. Vector. just for testing
byte[] iv = "e675f725e675f725".getBytes("UTF-8");
c.init(mode, generateKey(), new IvParameterSpec(iv));
return c;
}
private static String Decrypt(String encrypted) throws Exception {
byte[] decodedValue = new Base64().decode(encrypted.getBytes("UTF-8")); // new BASE64Decoder().decodeBuffer(encrypted);
Cipher c = getCipher(Cipher.DECRYPT_MODE);
byte[] decValue = c.doFinal(decodedValue);
return new String(decValue);
}
private static Key generateKey() throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = "3x5FBNs!".toCharArray();
byte[] salt = "S#1tS#1t".getBytes("UTF-8");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
byte[] encoded = tmp.getEncoded();
return new SecretKeySpec(encoded, "AES");
}
I tried to use RNCryptor but could not decrypt. Can anybody help me which library should i use because i have got the encrypted file and don't know how it has been encrypted.
In order to use RNCryptor it is best to use it on both platforms.
From a previous question it seems that the encrypted data was bytes, not Base64 encoded.
The primitives supplied by Apple Common Crypto and are part of the Security.framework. The header to use is #import <CommonCrypto/CommonCrypto.h> and you will find the interfaces you need in CommonCryptor.h and CommonKeyDerivation.h.
Make an attempt for iOS and add the code along with hex dumps of all input and output parameters and data both for the Android and iOS code.

Getting Data from a Website using MVC 4 Web API

This is a follow-up to this post: New at MVC 4 Web API Confused about HTTPRequestMessage
Here is a summary of what I am trying to do: There is a web site that I want to interface with via MVC 4 Web API. At the site, users can log in with a user name and password, then go to a link called ‘Raw Data’ to query data from the site.
On the ‘Raw Data’ page, there is a dropdown list for ‘Device’, a text box for ‘From’ date, and a text box for ‘To’ date. Given these three parameters, the user can click the ‘Get Data’ button, and return a table of data to the page. What I have to do, is host a service on Azure that will programmatically provide values for these three parameters to the site, and return a CSV file from the site to Azure storage.
The company that hosts the site has provided documentation to programmatically interface with the site to retrieve this raw data. The document describes how requests are to be made against their cloud service. Requests must be authenticated using a custom HTTP authentication scheme. Here is how the authentication scheme works:
Calculate an MD5 hash from the user password.
Append the request line to the end of the value from step one.
Append the date header to the end of the value in step two.
Append the message body (if any) to the end of the value in step 3.
Calculate MD5 hash over the resulting value from step 4.
Append the value from step 5 to the user email using the “:” character as a delimiter.
Calculate Base64 over the value from step 6.
The code that I am going to list was done in Visual Studio 2012, C#, .NET Framework 4.5. All of the code in this post is in my 'FileDownloadController.cs' Controller class. The ‘getMd5Hash’ function takes a string, and returns an MD5 hash:
//Create MD5 Hash: Hash an input string and return the hash as a 32 character hexadecimal string.
static string getMd5Hash(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
This function takes a string, and returns BASE64:
//Convert to Base64
static string EncodeTo64(string input)
{
byte[] str1Byte = System.Text.Encoding.ASCII.GetBytes(input);
String plaintext = Convert.ToBase64String(str1Byte);
return plaintext;
}
The next function creates an HTTPClient, makes an HTTPRequestMessage, and returns the authorization. Note: The following is the URI that was returned from Fiddler when data was returned from the ‘Raw Data’ page: GET /rawdata/exportRawDataFromAPI/?devid=3188&fromDate=01-24-2013&toDate=01-25-2013 HTTP/1.1
Let me first walk through what is happening with this function:
The ‘WebSiteAuthorization’ function takes a ‘deviceID’, a ‘fromDate’, a ‘toDate’ and a ‘password’.
Next, I have three variables declared. I’m not clear on whether or not I need a ‘message body’, but I have a generic version of this set up. The other two variables hold the beginning and end of the URI.
I have a variable named ‘dateHeader’, which holds the data header.
Next, I attempt to create an HTTPClient, assign the URI with parameters to it, and then assign ‘application/json’ as the media type. I’m still not very clear on how this should be structured.
In the next step, the authorization is created, per the requirements of the API documentation, and then the result is returned.
public static string WebSiteAuthorization(Int32 deviceid, string fromDate, string toDate, string email, string password)
{
var messagebody = "messagebody"; // TODO: ??????????? Message body
var uriAddress = "GET/rawdata/exportRawDataFromAPI/?devid=";
var uriAddressSuffix = "HTTP/1.1";
//create a date header
DateTime dateHeader = DateTime.Today;
dateHeader.ToUniversalTime();
//create the HttpClient, and its BaseAddress
HttpClient ServiceHttpClient = new HttpClient();
ServiceHttpClient.BaseAddress = new Uri(uriAddress + deviceid.ToString() + " fromDate" + fromDate.ToString() + " toDate" + toDate.ToString() + uriAddressSuffix);
ServiceHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//create the authorization string
string authorizationString = getMd5Hash(password);
authorizationString = authorizationString + ServiceHttpClient + dateHeader + messagebody;
authorizationString = email + getMd5Hash(authorizationString);
authorizationString = EncodeTo64(authorizationString);
return authorizationString;
}
I haven’t tested this on Azure yet. I haven't completed the code that gets the file. One thing I know I need to do is to determine the correct way to create an HttpRequestMessage and use HttpClient to send it. In the documentation that I've read, and the examples that I've looked at, the following code fragments appear to be possible approaches to this:
Var serverAddress = http://my.website.com/;
//Create the http client, and give it the ‘serverAddress’:
Using(var httpClient = new HttpClient()
{BaseAddress = new Uri(serverAddress)))
Var requestMessage = new HttpRequestMessage();
Var objectcontent = requestMessage.CreateContent(base64Message, MediaTypeHeaderValue.Parse (“application/json”)
or----
var formatters = new MediaTypeFormatter[] { new jsonMediaTypeFormatter() };
HttpRequestMessage<string> request = new HttpRequestMessage<string>
("something", HttpMethod.Post, new Uri("http://my.website.com/"), formatters);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpClient = new HttpClient();
var response = httpClient.SendAsync(request);
or------
Client = new HttpClient();
var request = new HttpRequestMessage
{
RequestUri = "http://my.website.com/",
Method = HttpMethod.Post,
Content = new StringContent("ur message")
};
I'm not sure which approach to take with this part of the code.
Thank you for your help.
Read this step by step tutorial to understand the basic.

Resources