Encrypting the user credentials using SHA1 algorithm - blackberry

I am creating a blackberry application which sends the request to the server. So authentication of the user is required. So for doing this i want to encrypt UserID and password using SHA1 in blackberry. The encrypted data which is made using SHA1 algorithm on UserID and password is then passed to the server.
My problem is how do i implement this. Can someone give the sample code for implementing this in blackberry.

SHA1 is not an encryption algorithm. It is hash-function.
http://en.wikipedia.org/wiki/SHA1
If you are talking about Basic Authentication, then you need to use Base64 algorithm to hash username and password.
Here is discussed topic about this issue: HTTP authentication in J2ME

add this class
public class Sha1 {
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text) {
SHA1Digest sha1Digest = new SHA1Digest();
sha1Digest.update(text.getBytes(), 0, text.length());
byte[] hashValBytes = new byte[sha1Digest.getDigestLength()];
hashValBytes = sha1Digest.getDigest();
return convertToHex(hashValBytes);
}
}
then on your code , Write
sha1 = Sha1.SHA1(email);

Related

IMAP OAuth2 with Chilkat

I was looking for a way to Authenticate an IMAP session with google's Service account
But Since we already use Chilkat how do we do it, I found the following:
http://www.cknotes.com/imap-authentication-using-oauth/
allowing me to send a raw command:
imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");
This shows how to strucure the command:
https://developers.google.com/gmail/xoauth2_protocol
But having trouble putting it all together.
limilabs puts things together nicely in this example:
http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
They have a neat imap.LoginOAUTH2(userEmail, credential.Token.AccessToken); that wraps things up into a command. How do I do this as a raw command for Chilkat?
const string serviceAccountEmail = "service-account-xxxxxx#developer.gserviceaccount.com";
const string serviceAccountCertPath = #"service-xxxxxx.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "user#domain.com";
X509Certificate2 certificate = new X509Certificate2(
serviceAccountCertPath,
serviceAccountCertPassword,
X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://mail.google.com/" },
User = userEmail
}.FromCertificate(certificate));
bool success = credential.RequestAccessTokenAsync(CancellationToken.None).Result;
using (Chilkat.Imap imap = new Chilkat.Imap())
{
imap.UnlockComponent("unlock-code");
imap.Ssl = true;
imap.Port = 993;
imap.Connect("imap.gmail.com");
var authString = String.Format("user={0}" + "\x001" + "auth=Bearer {1}" + "\x001" + "\x001",userEmail, credential.Token.AccessToken);
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
string response = imap.SendRawCommand("AUTHENTICATE XOAUTH2 " + encoded);
imap.SelectMailbox("Inbox");
bool bUid;
bUid = false;
string mimeStr;
int i;
int n;
n = imap.NumMessages;
for (i = 1; i <= n; i++)
{
// Download the email by sequence number.
mimeStr = imap.FetchSingleAsMime(i, bUid);
Chilkat.Email chilkatEmail = new Chilkat.Email();
chilkatEmail.SetFromMimeText(mimeStr);
Console.WriteLine(chilkatEmail.Subject);
}
imap.CloseMailbox("Inbox");
Console.ReadLine();
}
}

Thinktecture Identity Server with OAuth Implicit Login

I am trying to use javascript to login to identity server in OAuths Client. I can login and return to the return webpage successful.
I met a problem is why the Thinktecture identity sevrer always return '#' not '?' before parameters in querystring ,is that a bug?
the other question is how can I get the uses claims when I have access_token?
Implicit flow uses a hash fragment not a query string - that is not a bug (check the OAuth2 spec).
The client does not consume the access token in OAuth2 - it is opaque to the client - the access token is meant to be used by the backend.
I write a javascript function with regular expression to extract the "access_token" parameter as below:
var _access_token = getParameterByName('access_token');
function getParameterByName(name) {
var str = location.hash.substring(1);
var patt1 = new RegExp(name + "\\s*=\\s*([^&]+)", "g");
var result = patt1.exec(str);;
if (result == null)
return "";
else
return result[1];
}
then I try to use base64 to decode the access_token to get to extract the claims:
var Claims = base64decode(access_token)
function base64decode(input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
}

Retrieving OAuth Verification Code via .NET HttpWebRequest

I'm attempting to replicate the OAuth steps normally done via the "Connect to QuickBooks" button using HttpWebRequest/HttpWebResponse.
It's easy at first grabbing the request token and generating the authorization link:
private const string oauthBaseUrl = "https://oauth.intuit.com/oauth/v1";
private const string urlRequestToken = "/get_request_token";
private const string urlAccessToken = "/get_access_token";
private const string verifyUrl = "https://appcenter.intuit.com";
private const string authorizeUrl = "https://appcenter.intuit.com/Connect/Begin";
...
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(ckSS),
ConsumerSecret = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(csSS),
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession session = new OAuthSession(consumerContext, oauthBaseUrl + urlRequestToken, authorizeUrl, oauthBaseUrl + urlAccessToken);
IToken requestToken = session.GetRequestToken();
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);
Then I walk through grabbing the request verification code that is generated in the set-cookie string when requesting the site at the authorization link:
var requestAuth = (HttpWebRequest) WebRequest.Create(authorizationLink);
requestAuth.Method = "GET";
requestAuth.ContentType = "application/x-www-form-urlencoded";
requestAuth.Accept = "text/html, application/xhtml+xml, */*";
requestAuth.Headers.Add("Accept-Encoding", "gzip, deflate");
requestAuth.Headers.Add("Accept-Language", "en-us");
requestAuth.Host = "appcenter.intuit.com";
requestAuth.KeepAlive = true;
var responseAuth = (HttpWebResponse) requestAuth.GetResponse();
Stream answerAuth = responseAuth.GetResponseStream();
var _answerAuth = new StreamReader(answerAuth);
string htmlAuth = _answerAuth.ReadToEnd();
// Need to grab the request verification code embedded in the set-cookie string
string cookies = responseAuth.Headers.Get("Set-Cookie");
int idx = cookies.IndexOf("__RequestVerificationToken", StringComparison.Ordinal);
if (idx > 0)
{
int startIndex = cookies.IndexOf("=", idx, StringComparison.InvariantCultureIgnoreCase);
int endIndex = cookies.IndexOf(";", startIndex + 1, StringComparison.InvariantCultureIgnoreCase);
requestVerificationCode = cookies.Substring(startIndex + 1, endIndex - (startIndex + 1));
postDataString += requestVerificationCode;
}
As I understand it, the request verification code is needed in order to get the OAuth verification code that is returned in the postdata appended to the callback URL, which is in turn needed to get the access token.
This is where the difficulty begins. Using Fiddler2, I find that the login URL for generating the OAuth verification code is https://appcenter.intuit.com/Account/LogOnJson. But no matter how much I try to replicate the HTTP POST using HttpWebRequest, all I get in return is a 500 error. I'm wondering if anyone has a working example of this step? Is this even possible? I hope so, because the alternative of pulling up IE and walking through the same steps like a macro is too ugly.
Any help on this? Thanks!
You can download the dotnet sample app for understanding how the OAUTH flow works:
https://github.com/IntuitDeveloperRelations/IPP_Sample_Code
Set your app keys in web.config.

TCP client stream

I'm comunicationg with a email gateway. That gateway has an specific ip and port.
The requests the gateway are JSON formated and the gateway normally responds first whith an proceeding state and then with a confirmation or error state, represented also in JSON.
The code to make the requests and receive the response is:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Win32;
public class TcpClientSample
{
public static void SendMessage(TcpClient client, string msg)
{
Console.WriteLine("REQUEST:" + msg);
NetworkStream stream = client.GetStream();
byte[] myWriteBuffer = Encoding.ASCII.GetBytes(msg);
stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);
byte[] myWriteBuffer2 = Encoding.ASCII.GetBytes("\r\n");
stream.Write(myWriteBuffer2, 0, myWriteBuffer2.Length);
string gResponse = "";
BinaryReader r = new BinaryReader(stream);
int receivedMessages = 0;
while (true)
{
while (true)
{
char currentChar = r.ReadChar();
if (currentChar == '\n')
break;
else
gResponse = gResponse + currentChar;
}
if (gResponse != "")
{
Console.WriteLine("RESPONSE:" + gResponse);
receivedMessages = receivedMessages + 1;
}
if (receivedMessages == 2)
{
break;
}
}
}
public static void Main()
{
List<string> messages = new List<string>();
for (int i = 0; i < 1; i++)
{
String msg = "{ \"user\" : \"James\", \"email\" : \"james#domain.pt\" }";
messages.Add(msg);
}
TcpClient client = new TcpClient();
client.Connect("someIp", somePort);
int sentMessages = 0;
int receivedMessages = 0;
foreach (string msg in messages)
{
Thread newThread = new Thread(() =>
{
sentMessages = sentMessages + 1;
Console.WriteLine("SENT MESSAGES: " + sentMessages);
SendMessage(client, msg);
receivedMessages = receivedMessages + 1;
Console.WriteLine("RECEIVED MESSAGES: " + receivedMessages);
});
newThread.Start();
}
Console.ReadLine();
}
}
If I send few emails (up to 10) the network stream is OK.
But if I send thousands of emails I get messed chars lie
:{iyo"asn ooyes" "ncd" 0,"s_d:"4379" nme" 92729,"er_u" ,"ed_t_i" 2#" p cin_d:"921891010-11:11.725,"s" 4663175D0105E6912ADAAFFF6FDA393367" rpy:"rcein"
Why is this?
Don't worry I'm not a spammer :D
When you write a message to a TCP socket, it'll respond with the sent data. When the buffer is full, I expect it's 0, but you advance your send buffer anyway. You should advance it by the return value :)
Edit: it looks like you're using a stream abstraction which writes the internal buffer. The situation is the same. You are saying "the message has been completely sent" when the internal buffer state is not saying this, i.e. position does not equal limit. You need to keep sending until the remaining amount of buffer is 0 before moving on.
I solved this issue by having a single method just to read from the stream like this:
private TcpClient client;
private NetworkStream stream;
public void ListenFromGateway()
{
...
while (true)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
//BLOCKS UNTIL AT LEAST ONE BYTE IS READ
stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
//RETURNS THE DATA RECEIVED
string returndata = Encoding.UTF8.GetString(bytes);
//REMOVE THE EXCEDING CHARACTERS STARTING ON \r
string returndata = returndata.Remove(returndata.IndexOf('\r'));
...
}
Thanks for the help

Getting a URL of a record from HP TRIM's Desktop Client

Is it possible to copy the URL of a Record/Document from HP's TRIM and sent it to someone in order to download?
Before TRIM 7, whether you can do this natively depends on which TRIM features are installed.
To see if you have the right stuff, make a TR5 file on your desktop, and rightclick on it - "TryURL" - copy the URL
(the TryURL right click action requires TRIM client stuff - if you don't have that, try opening the TR5 file in notepad, and see if there is a hyperlink in there).
You do get this functionality with the SharePoint connector for TRIM (TIPS or TSCI)
Or there is a cheap third party product that looks cool - from Icognition Pty Ltd.
There are a few ways of going about doing something like this. Assuming you're sending the link to someone on the same WAN, or the security-risky option of having your TRIM system internet accessible, what I'd do is build a simple web service over the top of the TRIM SDK. The TRIM SDK is COM (with a PIA wrapper) or a proper .Net assembly (in version 7.*), so a simple ASP.Net service would be quite easy.
Below is the code for an ASP.Net service I built, based on a code sample provided by HP (based on the TRIMSDKPIA20.dll, not the TRIM 7.0 HP.HPTRIM.SDK assembly). You could use it as a basis to make something more RESTful, but as it is, you'd call it using a URL like:
http://server/ViewRecord/recno=D11-001
You could then create an "External Link", an Addin based again on the SDK that you can register as a Right-Click option in the TRIM interface. Something like "Send Download URL..." that fires up an email and generates the URL, but that's a bit more complicated.
Anyway, the code for the webservice:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TRIMSDK;
using System.Configuration;
using Microsoft.Win32;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string errormsg = string.Empty;
//Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Database trim = new Database();
trim.SetAsWebService();
trim.Id = ConfigurationSettings.AppSettings["dbid"];
trim.WorkgroupServerName = ConfigurationSettings.AppSettings["wgserver"];
trim.WorkgroupServerPort = Int32.Parse(ConfigurationSettings.AppSettings["wgport"]);
trim.Connect();
string recno = Request.QueryString["recno"];
if (String.IsNullOrEmpty(recno))
{
errormsg = "No recno parameter was passed.";
}
else
{
Record rec = trim.GetRecord(recno);
if (rec == null)
{
errormsg = string.Format("Could not find a record with number \"{0}\". Either it doesn't exist, or you don't have permission to view it.", recno);
}
else
{
if (!rec.IsElectronic)
{
errormsg = string.Format("Record {0} does not have an electronic attachment", rec.Number);
}
else
{
IStream s = rec.GetDocumentStream(null, false, null);
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "filename=" + rec.SuggestedFileName);
Response.AddHeader("Content-Length", rec.DocumentSize.ToString());
Response.Buffer = false;
Response.ContentType = GetContentType(rec.Extension);
uint BufferSize = 10000;
uint DocumentLength = (uint)rec.DocumentSize;
byte[] buffer = new byte[BufferSize];
uint bytesread;
uint totalread = 0;
Stream outstream = Response.OutputStream;
while (totalread < DocumentLength)
{
s.RemoteRead(out buffer[0], 10000, out bytesread);
if (bytesread < 10000)
{
for (uint i = 0; i < bytesread; i++)
{
outstream.WriteByte(buffer[i]);
}
}
else
{
outstream.Write(buffer, 0, 10000);
}
totalread += bytesread;
}
outstream.Close();
Response.Flush();
return;
}
}
}
Response.Write(errormsg);
}
private string GetContentType(string fileExtension)
{
string ct = Registry.GetValue(#"HKEY_CLASSES_ROOT\." + fileExtension.ToLower(), "Content Type", string.Empty) as string;
if (ct.Length == 0)
{
ct = "application/octet-stream";
}
return ct;
}
}

Resources