How to sign data using blackberry cryptography - blackberry

I am trying to sign data using Blackberry cryptography but generated signature is not getting verify by the server side(PHP)
I tried this -
RSACryptoSystem rsaCryptoSystem = new RSACryptoSystem(1024);
// Create an RSA key pair.
RSAKeyPair rsaKeyPair = new RSAKeyPair( rsaCryptoSystem );
// Create the necessary RSA key pair for signing and verifying.
RSACryptoSystem cryptoSystem = new RSACryptoSystem(1024);
RSAKeyPair keyPair = new RSAKeyPair( cryptoSystem );
// Create the digest and the salt value.
SHA1Digest digest = new SHA1Digest();
byte[] salt = RandomSource.getBytes( digest.getDigestLength() );
// Create the RSASignatureSigner passing in a digest algorithm
// and PSS signature formatter.
PSSSignatureSigner signer =
new PSSSignatureSigner( rsaKeyPair.getRSAPrivateKey(), digest, salt );
signer.update( stringToSign.getBytes() );
// Encode the signature using X509.
EncodedSignature encSignature = SignatureEncoder.encode( signer,"X509" );
String signedIdentifier = Base64.encode(encSignature.getEncodedSignature());
Please help

Change your code with
byte[] dataBytes = stringToSign.getBytes();
PKCS1SignatureSigner signer = new PKCS1SignatureSigner(rsaKeyPair.getRSAPrivateKey());
signer.update(dataBytes, 0, dataBytes.length);
byte[] signatureBytes = new byte[signer.getLength()];
signer.sign(signatureBytes, 0);
String signedIdentifier = Base64.encode(signatureBytes);

Related

Create signature in nodejs algorithm rsa-sha1 private_key.pem

Can I create signature like code below in Nodejs?
# Load PRIVATE key
private_key = OpenSSL::PKey::RSA.new(File.read(Rails.root + ENV['EPAY_PRIVATE_KEY']))
# Sign your data
signMessage = private_key.sign(OpenSSL::Digest::SHA1.new, message)
# Base64 message
baseMessage = Base64.encode64(signMessage.to_s)
You should be able to do the same thing in Node.js, creating a signature is quite easy, for example:
const crypto = require('crypto');
const fs = require('fs');
const privateKey = fs.readFileSync('./private-key.pem', 'utf8');
const message = "some message data";
const sign = crypto.createSign('SHA1');
sign.update(message);
sign.end();
const signature = sign.sign(privateKey);
console.log("Signature: ", signature.toString('base64'));
This creates a base64 encoded SHA1 signature of the message.

I am writing 3DES (using SHA1 HASH) encryption algorithm using C #. Key size error

I am writing 3DES (using SHA1 HASH) encryption algorithm using C #.
Size error in tdes.Key = keyArray of the following code. I do not know what went wrong.
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
if (useHashing)
{
SHA1CryptoServiceProvider objSHA1CryptoService = new SHA1CryptoServiceProvider();
keyArray = objSHA1CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
objSHA1CryptoService.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
}

java.security.UnrecoverableKeyException : no match

I am facing one issue while integrating AWS Iot SDK in my Xamarin.Android app.
I am creating basic app just to connect to mqtt through AWS Iot to subscribe to topics and and publish messages to that topic.
I am getting "java.security.UnrecoverableKeyException:no match" in getTempKeystore method in AWSIotKeystoreHelper class.
I have created a bks file using bouncycastle which has both certificate and key.(I have created this certificate through AWS resource)
I have followed the exact same steps as mentioned in the link:
https://github.com/awslabs/aws-sdk-android-samples/tree/master/AndroidPubSub
Here is my code:
private static String CUSTOMER_SPECIFIC_ENDPOINT = "";
private static String COGNITO_POOL_ID = "";
private static String AWS_IOT_POLICY_NAME = "";
private static Regions MY_REGION = Regions.UsEast2;
private static String KEYSTORE_NAME = "";
private static String KEYSTORE_PASSWORD = "";
private static String CERTIFICATE_ID = "";
clientId = UUID.RandomUUID().ToString();
credentialsProvider = new CognitoCachingCredentialsProvider(
Android.App.Application.Context, // context
COGNITO_POOL_ID, // Identity Pool ID
MY_REGION // Region
);
Region region = Region.GetRegion(MY_REGION);
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
mqttManager.KeepAlive = 10;
AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("my/lwt/topic", "Android client lost connection", AWSIotMqttQos.Qos0);
mqttManager.MqttLastWillAndTestament = lwt;
mIotAndroidClient = new AWSIotClient(credentialsProvider);
mIotAndroidClient.SetRegion(region);
keystorePath = FilesDir.AbsolutePath;
keystoreName = KEYSTORE_NAME;
keystorePassword = KEYSTORE_PASSWORD;
certificateId = CERTIFICATE_ID;
if ((bool)AWSIotKeystoreHelper.IsKeystorePresent(keystorePath, keystoreName))
{
if ((bool)AWSIotKeystoreHelper.KeystoreContainsAlias(certificateId, keystorePath, keystoreName, keystorePassword))
{
clientKeyStore = AWSIotKeystoreHelper.GetIotKeystore(certificateId, keystorePath, keystoreName, keystorePassword);
}`
else
{
Log.Info(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
}
}
else
{
Log.Info(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
}`
I was able to resolve this issue.I was using openssl pkcs12 to convert the certificates and keys into .p12 format. And then using the bouncycastle jar to convert the .p12 keystore to .bks format as android supports only BKS format. Instead of using bouncycastle i used Portecle.I referred to the following links for all the further conversion process :
Downloading portecle
http://certificate.fyicenter.com/942_Portecle_Downloading_and_Installing_Portecle_1.7.html
Conversion from .p12 to .bks
http://portecle.sourceforge.net/change-keystore-type.html

Issue in IOS Push Notification - Authentication failed because the remote party has closed the transport stream

I am using the below code for push notification.
public void PushNotificationIOS(string message, string registrationKey)
{
string deviceID = registrationKey;
int port = 2195;
String hostname = System.Configuration.ConfigurationManager.AppSettings["HostName"];//"gateway.sandbox.push.apple.com";
string certPath = string.Empty;
certPath = System.Configuration.ConfigurationManager.AppSettings["CertificatePath"] + System.Configuration.ConfigurationManager.AppSettings["Cer
String certificatePath = System.Web.HttpContext.Current.Server.MapPath(certPath);
string certPassword = System.Configuration.ConfigurationManager.AppSettings["CertificatePassword"];
TcpClient client = new TcpClient(hostname, port);
try
{
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certPassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(StringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + message + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
}
I am getting the following error
Authentication failed because the remote party has closed the transport stream.
On Trace, I am getting the below
System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck)
at System.Net.Security.SslState.get_SecureStream()
at System.Net.Security.SslStream.Write(Byte[] buffer)
I tried all the things mentioned in various post but am not able to solve the issue.
Make sure certificate is valid & is not corrupted. You can regenerate certificate to be dead sure.
Try providing all the options for SecurityProtocolType like :
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls, false);
SecurityProtocolType.Tls12 can negotiate Transport layer security 1.1 or downwards too but try all options to be sure.
For more details on SecurityProtocolType refer :
https://msdn.microsoft.com/en-us/library/system.net.securityprotocoltype(v=vs.110).aspx

Create oauth_signture in flickr for getting access token

I am new to flickr API.Some where i get the code to create the signature for getting request token.but i cant able to create it for the access token.Always says that the signature is invalid.
i am using the code for creating signature is
private static String getreqSignature(String url, String params)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("GET&");
base.append(url);
base.append("&");
base.append(params);
System.out.println("Stirng for oauth_signature generation:" + base);
// yea, don't ask me why, it is needed to append a "&" to the end of
// secret key.
byte[] keyBytes = (ApplicationContext.getFLICKR_API_SECRET() + "&")
.getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
System.out.println(new String(base64.encode(mac.doFinal(base.toString()
.getBytes(ENC))), ENC));
// encode it, base64 it, change it to string and return.
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}
My query parameters are
qparams.add(new BasicNameValuePair("oauth_consumer_key","******"));
qparams.add(new BasicNameValuePair("oauth_nonce", ""+ (int) (Math.random() * 100000000)));
qparams.add(new BasicNameValuePair("oauth_signature_method","HMAC-SHA1"));
qparams.add(new BasicNameValuePair("oauth_timestamp", ""+ (System.currentTimeMillis() / 1000)));
qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
// generate the oauth_signature
String signature = getreqSignature(URLEncoder.encode(
"http://www.flickr.com/services/oauth/request_token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// qparams.add(new BasicNameValuePair("oauth_verifier", verifier));
qparams.add(new BasicNameValuePair("oauth_signature", signature));
URI uri = URIUtils.createURI("http", "www.flickr.com", -1,
"/services/oauth/request_token",
URLEncodedUtils.format(qparams, ENC), null);
How to create signature to get access token.What to change in the above code.
finally i used Scribe library to get my details.Its working fine.

Resources