Swift SHA1 function without HMAC - javascript

i try to get SHA1 working in swift.
without using CommonCrypto since it is not default in swift.
please see https://gist.github.com/wdg/f7c8c4088030c59f0f45 (since it's a little to big to post)
if i run a test case in Xcode:
func test_sha1() {
XCTAssertEqual(sha1("test"), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3")
}
it will fail, and return 2d891cc96e32c32e8d26704d101208b954f435a5
i got the hash with:
$ php -r "echo sha1('test');echo(PHP_EOL);"
a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
i think the problem is that in the javascript file they use >>> and i don't know what this operator is.
So i have used >>.
i hope someone can help.
Thanks in advance

Use Common Crypto for several reasons: 1. It is correct. 2. It is FIPS 140-2 certified. 3. It is over 1000 times faster than a code based Swift implementation.
Note: Common Crypto uses the hardware encryption engine.
Just add a bridging header with the include:
#import <CommonCrypto/CommonCrypto.h>
Example code for SHA256 (SHA1 should no longer be used):
func sha256(dataIn dataIn:NSData) -> NSData {
let digest: NSMutableData! = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH));
CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes));
return digest;
}
or
func sha1(dataIn dataIn:NSData) -> NSData {
let digest: NSMutableData! = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH));
CC_SHA1(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes));
return digest;
}
or
func sha1(string string: String) -> [UInt8] {
var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
}
return digest
}

I've got a solution, there was something wrong with the rotate function.
i have changed the rotate function to
func rotate(n: Int, _ s: Int) -> Int {
return ((n << s) & 0xFFFFFFFF) | (n >> (32 - s))
}
and now it works.

Related

How to pass array of strings between javascript and C/C++ code with webassembly/emscripten?

I am trying to write a web application that will do sort of word processing (say spell check, grammar check, word analysis) using back-end C/C++ code. (I have got c/C++ code working in another desktop app... I want to bring it to web).
I want an example minimal code doing this (pass array of strings from JavaScript to c/c++ code...c/c++ code will do the word operations... I have this code ......and the resulting array of strings will be sent back to JavaScript where they will be processed further. (passing arrays to and from is important)
Please point me to any such code/tutorial, from where I can make a start.
I searched GitHub. I found several projects using emscripten but could not get this anywhere. (Only place I could get some clue was Hunspell built with emscripten ... however I could not build it successfully)
Please let me know . Thanks in advance.
First prepare the C++ side to receive a string (character array):
static char *string_buffer = NULL;
static size_t string_length = 0;
void EMSCRIPTEN_KEEPALIVE string_start_js(void) {}
void EMSCRIPTEN_KEEPALIVE string_final_js(void) {}
char * EMSCRIPTEN_KEEPALIVE string_ensure(size_t length)
{
// ensure that the buffer is long enough
if (length <= string_length) return string_buffer;
// grow the buffer
char *new_buffer = realloc(string_buffer, length + 1);
// handle the out of memory
if (new_buffer == null) return NULL;
// remember
string_buffer = new_buffer;
string_length = length;
// done
return string_buffer;
}
void EMSCRIPTEN_KEEPALIVE string_handle(size_t length)
{
// sanity
if (string_buffer == NULL || length > string_length) halt;
// terminate
string_buffer[length] = 0;
// work with the string characters, store/process it
}
void EMSCRIPTEN_KEEPALIVE string_clear(void)
{
// friendly
if (string_buffer == NULL) return;
// free
free(string_buffer);
// remember
string_buffer = NULL;
string_length = 0;
}
From the JavaScript side send one string to the C++ side:
let strings = ["abc", "defg", "1"];
// inform the C++ side that some strings are going to be transferred
exports['string_start_js']();
// send all strings
for (var i = 0; i < strings.length; i++)
{
// single string to transport
let string = strings[i];
// convert to a byte array
let string_bytes = new TextEncoder().encode(string);
// ensure enough memory in the C++ side
let string_offset = exports["string_ensure"](string_bytes.byteLength);
// handle the out of memory
if (string_offset == 0) throw "ops...";
// have view of the instance memory
let view = new Uint8Array(memory.buffer, string_offset, string_bytes.byteLength);
// copy the string bytes to the memory
view.set(string_bytes);
// handle
exports['string_handle'](string_bytes.byteLength);
}
// inform the C++ side that all strings were transferred
exports['string_final_js']();
// clear the used buffer
exports['string_clear']();
The way from C++ to WASM can be more simple:
have a character array (pointer) and its length
call an import function to give the array pointer to JavaScript and its length
make a view of the memory
read the characters from the view
Something like this in the C++ side:
extern "C" {
extern void string_start_cpp(void);
extern void string_final_cpp(void);
extern void string_fetch(char *pointer, size_t length);
}
void foo(void)
{
// inform the JavaScript side that
string_start_cpp();
// runtime string
const char *demo = "abc";
// send to JavaScript
string_fetch(demo, strlen(demo));
// inform the JavaScript side all strings were send
string_final_cpp();
}
And in JavaScript supply the functions during the instance creation:
string_start_cpp: function(offset, length)
{
console.log("{");
},
string_final_cpp: function(offset, length)
{
console.log("}");
},
string_fetch: function(offset, length)
{
// view the bytes
let view = new Uint8Array(memory.buffer, offset, length);
// convert the UTF-8 bytes to a string
let string = new TextDecoder().decode(view);
// use
console.log(string);
}
I did not test the code, there could be some syntax errors. You can improve in many places the code, but the idea is what counts.

unresolved symbol: llvm_trap from Emscripten

When I tried to compile the following snippet into WebAssembly binary, I kept hitting the unresolved symbol: llvm_trap warning, which makes the wasm code not consumable from JS.
emcc test.c -s WASM=1 -s ONLY_MY_CODE=1 -s "EXPORTED_FUNCTIONS=['_test']" -O2 -g -o test.js
test.c (This is a test code to reproduce the issue without doing meaningful jobs.)
int test(int *buf) {
int C = 1;
// Assuming WebAssembly.Memory buffer has been preloaed with data.
// *T represents the preloaded data here. And We know *T and *buf
// won't overlap in memory.
int *T = 0;
int index = C ^ buf[5];
int right = T[index];
int left = (unsigned)C >> 8;
// warning disappears if this is commented out. But why?
C = left ^ right;
return C;
}
I didn't write any llvm_trap related code. Does someone have ideas what does it mean?
The variable T must be initialised. If it represents an array that 'maps' to the WebAssembly linear memory, you can define it as a global as follows:
int T[1000];
int test(int *buf) {
int C = 1;
int index = C ^ buf[5];
int right = T[index];
int left = (unsigned)C >> 8;
// warning disappears if this is commented out. But why?
C = left ^ right;
return C;
}
This compiles without the llvm_trap warnings.
For more detail on how to pass data to a WASM function using linear memory, see the following question:
How to access WebAssembly linear memory from C/C++

Javascript to C++: Object Equivalent?

I've been tasked with converting some code from javascript to C++. While I'm decently familiar with Javascript, I'm pretty inexperienced with C++.
The javascript code heavily makes use of objects. For example the following code is used to convert angles from degrees to any other specified unit:
var allConversions = {
"Angle": {
"degrees": {
"degrees":function(inputNum) { return inputNum*1},
"minutes":function(inputNum) { return inputNum*60},
"radians":function(inputNum) { return inputNum*0.0174532925},
"revolutions":function(inputNum) { return inputNum*0.00277777778},
"seconds":function(inputNum) { return inputNum*3600},
}
}
exports.convertUnits= function(unitType, inUnit, outUnit, inputVal) {
return allConversions[unitType][inUnit][outUnit] (inputVal);
}
I'm wondering what is the best practice for how to create something similar in C++? Should I try and create something similar with a struct or class?
Not exactly sure what all the down votes are about. I see nothing wrong with your question.
JavaScript is a typeless language, and it's a bit... flexible in it's construction of objects. Depending on the actual code, you have two options and you'll want to use a mix of both.
Option 1: Create a Class
In this case, you'd create a class for the specific data structure, with properties for each value you need.
Use this when the JavaScript object is consistent throughout all it's uses.
Option 2: Use a Hash Map
There are a variety of different hash map classes. Which you choose is up to the specific version and framework(s) you're using.
Regardless though, these generally work like a JavaScript object, where you can create key/value pairs. Use this when your not quite sure what you're data will be.
Depends a lot on overall structure and context - that is missing in your code snippet. Probably, a simple class with some inline functions would do. But if I had to attempt an equivalent code as provided, I'd have to write something like this:
someClass.hpp
#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <string>
using std::string;
class degrees
{
public:
double inputVal;
degrees(string, string, string, double); // a constructor
double degreesFunc(double); // double?, can't have same name func
double minutes(double);
double radians(double);
double revolutions(double);
double seconds(double);
};
class Angle : public degrees
{
public:
Angle(string, string, string, double);
};
class allConversions : public Angle
{
public:
allConversions(string, string, string, double);
};
#endif /* SOMECLASS_H */
someClass.cxx
#include "someClass.hpp"
degrees::degrees(
string unitType,
string inUnit,
string outUnit,
double inputVal)
{
this->inputVal = inputVal;
}
double degrees::degreesFunc(double inputNum)
{
return inputNum*1;
}
double degrees::minutes(double inputNum)
{
return inputNum*60;
}
double degrees::radians(double inputNum)
{
return inputNum*0.0174532925;
}
double degrees::revolutions(double inputNum)
{
return inputNum*0.00277777778;
}
double degrees::seconds(double inputNum)
{
return inputNum*3600;
}
//-------------------------------------------------
Angle::Angle(
string a,
string b,
string c,
double d)
: degrees(a, b, c, d) { }
allConversions::allConversions(
string a,
string b,
string c,
double d)
: Angle(a, b, c, d) { }
test.cpp
#include <iostream>
#include "someClass.hpp"
using std::cout;
int main()
{
allConversions convertUnits("what?", "what?", "what?", 10);
cout << convertUnits.inputVal << '\n';
cout << convertUnits.radians(10) << '\n';
cout << convertUnits.minutes(10) << '\n';
}
Compiling with g++ with Makefile:
all:
g++ -c someClass.cxx
g++ -c test.cpp
g++ someClass.o test.o -o run
Run: ./run

Javascript isPunct function

I'm currently coding a Command Line program for function isPunct in Javascript and struggling to both start & completely finish it. Here's what I have so far:
function isPunct(str) {
var str = ".,:!?;";
if (/\pPunct/.test(str)) {
alert("Character is punctuation")
}
else {
alert("Character is not punctuation")
}
}
It's going through the console just fine, but isn't actually picking out the punctuation. Please help if you can! And thanks in advance.
function isPunct() {
//var str = "a.,:!?;"; -> false because of a
var str = ".,:!?;";
if (/^(\.|\,|\!|\?|\:|\;|\"|\'|\-|\(|\))*$/g.test(str)) {
alert("Character is punctuation")
}
else {
alert("Character is not punctuation")
}
}
isPunct();
It looks as if you were attempting to use Unicode property escapes (\p{UnicodePropertyName=UnicodePropertyValue}), which are not currently a part of the JavaScript standard. There is a proposal to add this functionality, but it has thus far only reached stage 2 of the TC39 process.
However, Mathias Bynens has created a wonderful tool called regexpu that will transpile these property escapes to their standard equivalents. I doubt all of the codepoints in the result are necessary to you, so feel free to shorten the list of characters as you see fit.
(Permalink to the ES5 equivalent of /^\p{Punctuation}*$/u.)
var onlyPunctuation = /^(?:[!-#%-\*,-/:;\?#\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F])*$/
function isPunct (string) {
return onlyPunctuation.test(string)
}
console.log(isPunct('.,:!?;')) //=> true
console.log(isPunct('letters')) //=> false

Eval alternative

This code works as a calculator, but the scratch pad at codeacademy tells me that eval is evil. Is there another way to do the same thing without using eval?
var calculate = prompt("Enter problem");
alert(eval(calculate));
eval evaluates the string input as JavaScript and coincidentally JavaScript supports calculations and understands 1+1, which makes it suitable as a calculator.
If you don't want to use eval, which is good, you have to parse that string yourself and, finally, do the computation yourself (not exactly yourself though). Have a look at this math processor, which does what you want.
Basically what you do is:
Read the input string char by char (with this kind of problem it's still possible)
Building a tree of actions you want to do
At the end of the string, you evaluate the tree and do some calculations
For example you have "1+2/3", this could evaluate to the following data structure:
"+"
/ \
"1" "/"
/ \
"2" "3"
You could then traverse that structure from top to bottom and do the computations.
At first you've got the "+", which has a 1 on the left side and some expression on the right side,
so you have to evaluate that expression first. So you go to the "/" node, which has two numeric children. Knowing that, you can now compute 2/3 and replace the whole "/" node with the result of that. Now you can go up again and compute the result of the "+" node: 1 + 0.66. Now you replace that node with the result and all you've got left is the result of the expression.
Some pseudo code on how this might look in your code:
calculation(operator, leftValue, rightValue):
switch operator {
case '+': return leftValue + rightValue
case '-': return 42
}
action(node):
node.value = calculation(node.operator, action(node.left) action(node.right))
As you might have noticed, the tree is designed in such a way that it honors operator precedence. The / has a lower level than the +, which means it get's evaluated first.
However you do this in detail, that's basically the way to go.
You can use the expression parser that is included in the math.js library:
http://mathjs.org
Example usage:
mathjs.evaluate('1.2 / (2.3 + 0.7)'); // 0.4
mathjs.evaluate('5.08 cm in inch'); // 2 inch
mathjs.evaluate('sin(45 deg) ^ 2'); // 0.5
mathjs.evaluate('9 / 3 + 2i'); // 3 + 2i
mathjs.evaluate('det([-1, 2; 3, 1])'); // -7
You can use eval safely for a simple arithmetic calculator by filtering the input- if you only accept digits, decimal points and operators (+,-,*,/) you won't get in much trouble. If you want advanced Math functions, you are better off with the parser suggestions.
function calculate(){
"use strict";
var s= prompt('Enter problem');
if(/[^0-9()*+\/ .-]+/.test(s)) throw Error('bad input...');
try{
var ans= eval(s);
}
catch(er){
alert(er.message);
}
alert(ans);
}
calculate()
I write some functions when I had a problem like this. Maybe this can help:
data = [
{id:1,val1:"test",val2:"test2",val2:"test3"},
{id:2,val1:"test",val2:"test2",val2:"test3"},
{id:3,val1:"test",val2:"test2",val2:"test3"}
];
datakey = Object.keys(data[0]);
// here's a fix for e['datakey[f]'] >> e[x]
vix = function(e,f){
a = "string";
e[a] = datakey[f];
x = e.string;
end = e[x];
delete e.string;
return end;
};
// here's a fix to define that variable
vox = function(e,f,string){
a = "string";
e[a] = datakey[f];
x = e.string;
end = e[x] = string;
delete e.string;
};
row = 2 // 3th row ==> {id:3,val1:"test",val2:"test2",val2:"test3"}
column = 1 //datakey 2 ==> val1
vox(data[row],column,"new value");
alert(data[2].val1); //the value that we have changed

Categories

Resources