Generate CHAP response in java - javascript

Currently I'm trying to generate a chap response in java. It works in php... but our backend needs it done in java.
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal)
I've managed to find some javascript code, but the response is off by a few characters.
function getPapPassword(){
//function to add value padding to a string of x length default : null padding
String.prototype.pad = function (length, padding) {
var padding = typeof padding === 'string' && padding.length > 0 ? padding[0] : '\x00'
, length = isNaN(length) ? 0 : ~~length;
return this.length < length ? this + Array(length - this.length + 1).join(padding) : this;
};
//function to convert hex to ascii characters
String.prototype.packHex = function () {
var source = this.length % 2 ? this + '0' : this
, result = '';
for (var i = 0; i < source.length; i = i + 2) {
result += String.fromCharCode(parseInt(source.substr(i, 2), 16));
}
return result;
};
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal);
}
return response;
}
Can anyone point me in the right direction or assist?
Thanks
Okay so what I've done is tried to convert from hex to ascii in java... here is my code.
public class App{
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
public static void main(String[] args) {
App app = new App();
System.out.println("ASCII : " + app.convertHexToString("9f9585f4e88305fde280c762925f37af"));
}
}
The php of the hex challenge output is: Ÿ•…ôèƒýâ€Çb’_7¯
The java output of the hex challenge is: ôèýâÇb_7¯
So I've found that the javascript is exactly the same as the java. Something is happening in php that is changing it. The php version works perfectly when I connect to the UAM with that chap response.

Related

Stuck converting Javascript function to VB.Net

I need help converting the following JS-function to vb.net please:
function testjs(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
What my code looks like at the moment:
Private Function questionmarkop(ByVal ph As String, ByVal dictatcurr As String, ByVal ophoc As String) As String
Return If(ph = dictatcurr, dictatcurr, ophoc)
End Function
Private Function testvb(ByVal s As String) As String
Dim dict As New Dictionary(Of Integer, String)
Dim data As Char() = s.ToCharArray
Dim currchar As Char = data(0)
Dim oldphrase As String = currchar
Dim out As String() = {currchar}
Dim code As Integer = 256
Dim phrase As String = ""
Dim ret As String = ""
For i As Integer = 1 To data.Length - 1
Dim currcode As Integer = Convert.ToInt16(data(i))
If currcode < 256 Then
phrase = data(i)
Else
phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar))
End If
ReDim Preserve out(out.Length)
out(out.Length - 1) = phrase
currchar = phrase(0)
dict.Item(code) = oldphrase + currchar
code += 1
oldphrase = phrase
Next
For Each str As String In out
ret = ret + str
Next
Return ret
End Function
When inputting the following string s: thisĂaveryshorttestđringtogiĆanexamplefČđackoĆrflow
The function should return: thisisaveryshortteststringtogiveanexampleforstackoverflow
The js function does exactly that, my vb function does not sadly.
The first time (or basically everytime) the if statement is not true, the next character will be wrong. So i figure there is something wrong with the line phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar)).
With the test string i provided everything works until this, after that i have the first false char.
Can someone help me figure out what i am doing wrong here?
Based on discussion in the comments, it seems like the issue was producing a VB translation for this line:
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
I have only passing familiarity with Javascript, but I believe the key here is that dict[currCode] will return a type of null or missing value if there is not already an entry in the dictionary with key currCode. The .NET dictionary has facilities that will let you get the same effect, though the exact implementation is a little different.
The direct VB equivalent to this ternary and assignment is (I believe):
phrase = If(dict.ContainsKey(currCode), dict(currCode), oldPhrase & currChar)
You can eliminate a key lookup on the dictionary by using Dictionary.TryGetValue:
If Not dict.TryGetValue(currCode, phrase) Then
phrase = oldPhrase & currChar
End If
I doubt the code is performance-sensitive enough to care about the difference, so I would recommend to use the alternative that you find more clear to read.

Replication of HMACSHA256 in c# as that of jsSHA

so i am trying to get this hash 69F6617707D9442940C39BEBFA0B4459CEBF6CD5E610EA1FF44B341E291654A9 which can me made on https://caligatio.github.io/jsSHA/.
The key is K = E74A540FA07C4DB1B46421126DF7AD36 , Message is T= 537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B and the generated hash via my code is SHA256 (T) = 6a2783d8eb0237e015f7dcd27fb2d2a85dd637220433dffcdc31198670f6ecac
This is incorrect Hash.
This is my code can someone explain what is wrong here thanks.
static void Main(string[] args)
{
var key = "E74A540FA07C4DB1B46421126DF7AD36";
string message = "537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B";
var encodingCred = new System.Text.ASCIIEncoding();
var encodingKey = new System.Text.ASCIIEncoding();
byte[] keyByte = StringToByteArray(key);
byte[] credentialsBytes = encodingCred.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(credentialsBytes);
string hash = BitConverter.ToString(hashmessage).Replace("-", string.Empty).ToLower();
Console.WriteLine("HASH: " + hash);
}
Console.ReadKey();
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
In C this is valid
void test_keyed_hmac()
{
hmac_sha256 hmac;
sha256 sha;
uint8_t sha_digest[32] = { 0 };
unsigned char key[] = "\xE7\x4A\x54\x0F\xA0\x7C\x4D\xB1\xB4\x64\x21\x12\x6D\xF7\xAD\x36";
//unsigned char key[] = "E74A540FA07C4DB1B46421126DF7AD36";
unsigned char data[] = "\x53\x77\x07\xAD\x48\x6F\x07\xAD\x75\xCC\xF7\xB1\xF7\xFE\xA6\xF7\x58\x71\xFC\xF6\xDC\x75\x59\x23\xC8\xEE\x7C\x37\x5C\x21\xEA\xC5\x1B\xD9\x7C\x51\xC6\x9F\x39\x5B";
//unsigned char data[] = "537707AD486F07AD75CCF7B1F7FEA6F75871FCF6DC755923C8EE7C375C21EAC51BD97C51C69F395B";
printf("Data length %d \n", strlen(data));
hmac_sha256_initialize(&hmac, key, strlen(key));
// Finalize the HMAC-SHA256 digest and output its value.
hmac_sha256_finalize(&hmac, data, strlen(data));
for (int i = 0; i < 32; ++i) {
// Cast added by RKW to get format specifier to work as expected
printf("%x", (unsigned long)hmac.digest[i]);
}
putchar('\n');
}
I need something like this in c# that gives the valid hash mentioned above in second line

Splitting string to list in Entity Framework

I have the following string :
DetailsParameters = "Id=1,UserId=1,2,3"
In entity framework stored procedure I am trying to split the above string as :
"Id=1" and "UserId=1,2,3"
Currently, I have the following code which is splitting the above mentioned string at comma which is incorrect.
if (DetailsParameters != "")
{
List<Details> adlist = new List<Details>();
DetailsParameters.Split(',').ToList().ForEach(delegate (string s)
{
adlist.Add(new Details()
{
AlarmLogId = AlarmLogId,
ParameterKey = s.Substring(0, s.IndexOf('=')),
ParameterValue = s.Substring(s.IndexOf('=') + 1, (s.Length - (s.IndexOf('=') + 1)))
});
});
context.Details.AddRange(adlist);
No need to get too complicated about it, you could do something like this:
//var DetailsParameters = "Id=1,UserId=1,2,3";
//var DetailsParameters = "UserId=1,2,3,Id=1";
var indexOf = DetailsParameters.IndexOf("UserId=");
//if the index of "UserId=" is at the start, it should find the other word "Id=" to split
if (indexOf == 0) indexOf = DetailsParameters.IndexOf("Id=", "UserId=".Length);
var firstParameter = DetailsParameters.Substring(0, indexOf);
var secondParameter = DetailsParameters.Substring(indexOf, DetailsParameters.Length - firstParameter.Length);
var firstParameterValue = firstParameter.Split('=')[1].Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries);
var secondParameterValues = secondParameter.Split('=')[1].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

Simply XOR encrypt in Javascript and Decrypt in Java

The purpose for this is not highly security-relevant and the key will be long, so I'm just wanting to use simple XOR encryption to the strings.
Well, the Javascript on the client is as follows:
function dc_encrypt(str, key)
{
var ord = []; var res = "";
var i;
for (i = 1; i <= 255; i++) {ord[String.fromCharCode(i)] = i}
for (i = 0; i < str.length; i++)
res += String.fromCharCode(ord[str.substr(i, 1)] ^ ord[key.substr(i % key.length, 1)]);
return(res);
}
And the Java is is:
public String dc_decrypt(String str, String key)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < str.length(); i++)
sb.append((char)(str.charAt(i) ^ key.charAt(i % (key.length()))));
return(sb.toString());
}
Unfortunately this produces some very weird results. Some letters differ after encrypting in JS, sending the result through a POST and decrypt in Java.
In every case it doesn't seem to be reliable.
I assume the issue must have something to do with encoding... does someone know a more reliable solution for this?
Huge thanks in advance! :)
When XOR-encoding two strings, the resulting XOR-values of the individual characters sometimes do not result in characters that can be displayed.
Therefore one solution is to encode the result as a sequence of hex-values and then to decode these hex-values on the server side.
Javascript:
function encryptStringWithXORtoHex(input,key) {
var c = '';
while (key.length < input.length) {
key += key;
}
for(var i=0; i<input.length; i++) {
var value1 = input[i].charCodeAt(0);
var value2 = key[i].charCodeAt(0);
var xorValue = value1 ^ value2;
var xorValueAsHexString = xorValue.toString("16");
if (xorValueAsHexString.length < 2) {
xorValueAsHexString = "0" + xorValueAsHexString;
}
c += xorValueAsHexString;
}
return c;
}
Java-Code:
private static String decryptStringWithXORFromHex(String input,String key) {
StringBuilder c = new StringBuilder();
while (key.length() < input.length()/2) {
key += key;
}
for (int i=0;i<input.length();i+=2) {
String hexValueString = input.substring(i, i+2);
int value1 = Integer.parseInt(hexValueString, 16);
int value2 = key.charAt(i/2);
int xorValue = value1 ^ value2;
c.append(Character.toString((char) xorValue));
}
return c.toString();
};
Example:
Encode in Javascript:
encryptStringWithXORtoHex('Encrypt This','SecretKey');
returns the string 160b00001c043f452d3b0c10
Decrypting in Java:
decryptStringWithXORFromHex("160b00001c043f452d3b0c10","SecretKey")
returns Encrypt This
Please note: the shown solution only works for characters that have a charChode value of less or equal than 255. If you want to use the solution for unicode characters (e.g. €) you will have to change the code to take care of this.

make json string to match exact string for pie chart datasource?how to

here is my recieved JSON string
"{Date:'15/05/2015',y:'6'},
{Date:'01/08/2015',y:'6'},
{Date:'02/08/2015',y:'6'},
{Date:'08/08/2015',y:'72'},
{Date:'09/08/2015',y:'6'},"
i have to make it exactly like that for my datasource in pie chart
var datas = [
{date:"02/02/2015",y:6},
{date:"15/05/2015",y:6},
{date:"01/08/2015",y:6},
{date:"02/08/2015",y:6}
];
here is working js fiddle js fiddle working for json
here is my c sharp code for making json
foreach (KeyValuePair<string, int> pair2 in dic)
{
int perce = pair2.Value;
var perct = ((double)perce / total) * 100;
int perc = Convert.ToInt32(perct);
string datesval = pair2.Key;
StringBuilder sb = new StringBuilder();
sb.Append("Date:'" + datesval + "',y:" + perc + "");
string newq = sb.ToString();
list.Add(newq);
}
StringBuilder sb2 = new StringBuilder();
foreach (string element in list)
{
for (int m = 0; m <= list.Count() - 1; m++)
{
sb2.Append("{" + list[m] + "},");
line = sb2.ToString();
}
break;
}
the string should be modified using javascript
remove (") double quote from start of string and add [ . also remove (,") from end and add ]
also show error Uncaught TypeError: undefined is not a function on line
$('#container').highcharts({
use string builder and eval , I am extentendinng the above from Line you built
string c = line;
StringBuilder builder = new StringBuilder(c);
// builder.Replace(",\"","]");
// builder[0] = '[';
TrimEnd(builder,',');
// builder.AppendFormat("[\"{0}\"]", builder.ToString());
string combine = "["+ builder.ToString();
string newcom = combine + "]";
return newcom;
}
static void TrimEnd(StringBuilder builder, char letter)
{
// ... If last char matches argument, reduce length by 1.
if (builder.Length == 0)
{
string c = "sorry";
}
else if (builder[builder.Length - 1] == letter)
{
builder.Length -= 1;
}
}
in succes of ajax do this
var v = eval(response.d);
now use this in pie chart
2nd error is because jquery files conflict with each other use jquery 1.9.1.js first then graph files

Categories