I'm implementing a github push hook listener in dart, and I've come across this document: https://developer.github.com/webhooks/securing/
where it's written:
Using a plain == operator is not advised. A method like secure_compare
performs a “constant time” string comparison, which renders it safe
from certain timing attacks against regular equality operators.
I have to compare 2 hashes for equality. Now I was wondering if there was a way to compare string in constant time in dart? (read: is there a string constant time compare function in dart?)
The default implementation is not constant time, but you can just create your own comparison function that compares every code unit in the String and does not short circuit:
bool secureCompare(String a, String b) {
if(a.codeUnits.length != b.codeUnits.length)
return false;
var r = 0;
for(int i = 0; i < a.codeUnits.length; i++) {
r |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
}
return r == 0;
}
This function will perform a constant time String compare as long as the two input Strings are of the same length. Since you are comparing hashes this shouldn't be a problem, but for variable length Strings this method will still leak timing info because it immediately returns if the lengths are not equal.
Related
Given the following hash function (written in java):
long hash(String key) {
char[] c = key.toCharArray();
long hash = 7;
for (int i = 0; i < c.length; i++) {
hash = hash*31 + c[i];
}
return hash;
}
(note: I would have put the type of this hash function in the question title but couldn't find out what it's called. If you know the term please let me know in the comments)
How can one compute a key that gets hashed to the same value as some other key?
long a = hash("myKey");
String x = reverseHash(a);
assert(hash(x) == a);
Is there a way to compute this efficiently? (not looking for a decryption algorithm, only for a way to produce an equivalent hash)
How would such an algorithm look like? (doesn't have to use the exact same numbers as my example, I just want to understand it)
Some languages do not have support for unsigned integers, like dart or Java.
I have two integer numbers int a, b that are really unsigned (basically hashes or bitfields), but have to be stored in the signed data types.
A comparison function is needed. The usual a < b will not work here, as it would wrongly interpret negative values to be smaller, while they are (in the desired unsigned interpretation) actually larger. Each of those two ranges are handled correctly if considered alone.
A working solution I came up with (in dart, but language shouldn't really matter) is
int compareAsUnsigned(int a, int b) {
final signA = a.sign;
final signB = b.sign;
if (signA == signB) return a.compareTo(b);
if (signA == -1 || signB == -1) return b.compareTo(a);
return a.compareTo(b);
}
Are there any efficent and / or elegant ways to get the unsigned compare for values stored in signed data types (a longer type is not available and all bits are used)?
I am working with a C function in my Swift code that outputs an array. The function doesn't return an array because, apparently in C, functions are discouraged from returning arrays. Therefore, the function takes an in-out parameter (as a pointer) and places the array there.
The C function:
void kRing(H3Index origin, int k, H3Index* out);
H3Index* is the out parameter that takes the array. However, how do I get the array from this function in Swift? H3Index*, the out parameter, points to an integer. And, apparently in C, you can point to an integer, pass that pointer to a function, and that function can place an array in that pointer's place (even though it's pointing to an integer).
But because of Swift's type safety, this makes it difficult to get the array from the function. The Swift version:
kRing(origin: H3Index, k: Int32, out: UnsafeMutablePointer<H3Index>!)
My Swift implementation:
let h3Index: H3Index = 600022775385554943 // integer
let k: Int32 = 2 // integer
var result = H3Index() // the in-out parameter (must be integer to satisfy Swift's type safety)
_ = withUnsafeMutablePointer(to: &result) { kRing(h3Index, k, $0) }
print(result)
And it prints the result (with a bad access error, which I don't care about right now). But the result is an integer when it should be an array. How is this done?
The C implementation, for reference:
H3Index indexed = 0x8a2a1072b59ffffL; // 64-integer (hex)
int k = 2; // integer
int maxNeighboring = maxKringSize(k); // integer
H3Index* neighboring = calloc(maxNeighboring, sizeof(H3Index)); // the out parameter (a pointer to an integer and/or array)
kRing(indexed, k, neighboring); // the function
for (int i = 0; i < maxNeighboring; i++) {
if (neighboring[i] != 0) {
// iterate through array
}
}
In C,
H3Index* neighboring = calloc(maxNeighboring, sizeof(H3Index));
kRing(indexed, k, neighboring);
allocates memory for maxNeighboring elements of type H3Index and initializes the memory to zero. The address of that memory block (which is the address of the first element) is then passed to the kRing function.
It is possible to call calloc and free from Swift, but the easier to use API is Unsafe(Mutable)(Buffer)Pointer with its allocate() and deallocate() methods:
let neighboring = UnsafeMutableBufferPointer<H3Index>.allocate(capacity: maxNeighboring)
neighboring.initialize(repeating: 0)
kRing(indexed, k, neighboring.baseAddress)
Now you can print the values with
for i in 0..<maxNeighboring { print(neighboring[i]) }
or justs (because Unsafe(Mutable)BufferPointer is a collection that can be iterated over):
for neighbor in neighboring { print(neighbor) }
Eventually you must release the memory to avoid a memory leak:
neighboring.deallocate()
A simpler solution is to define a Swift array, and pass the address of the element storage to the C function:
var neighboring = Array<H3Index>(repeating: 0, count: maxNeighboring)
kRing(indexed, k, &neighboring)
for neighbor in neighboring { print(neighbor) }
neighboring is a local variable now, so that the memory is automatically released when the variable goes out of scope.
I am well aware that one is able to assign a value to an array or constant in Swift and have those value represented in different formats.
For Integer: One can declare in the formats of decimal, binary, octal or hexadecimal.
For Float or Double: One can declare in the formats of either decimal or hexadecimal and able to make use of the exponent too.
For instance:
var decInt = 17
var binInt = 0b10001
var octInt = 0o21
var hexInt = 0x11
All of the above variables gives the same result which is 17.
But what's the catch? Why bother using those other than decimal?
There are some notations that can be way easier to understand for people even if the result in the end is the same. You can for example think in cases like colour notation (hexadecimal) or file permission notation (octal).
Code is best written in the most meaningful way.
Using the number format that best matches the domain of your program, is just one example. You don't want to obscure domain specific details and want to minimize the mental effort for the reader of your code.
Two other examples:
Do not simplify calculations. For example: To convert a scaled integer value in 1/10000 arc minutes to a floating point in degrees, do not write the conversion factor as 600000.0, but instead write 10000.0 * 60.0.
Chose a code structure that matches the nature of your data. For example: If you have a function with two return values, determine if it's a symmetrical or asymmetrical situation. For a symmetrical situation always write a full if (condition) { return A; } else { return B; }. It's a common mistake to write if (condition) { return A; } return B; (simply because 'it works').
Meaning matters!
I'm adding strings to a window, with waddwstr() function, one line after other, in consecutive rows. I don't want ncurses to automatically wrap lines for me – I'm overwriting them with consecutive calls to waddwstr() and sometimes tail of previous line is left displaying. Can ncurses just stop when right edge of window is reached?
The non-wrapping functions have "ch" in their name, e.g., wadd_wchstr.
The same is true of the non-wide interfaces waddstr versus waddchstr.
However, the wrapping/non-wrapping functions differ by more than that. They use different parameter types. The wrapping functions rely upon the video attributes set via wattr_set, etc., while the non-wrapping functions combine the video-attributes with the character data:
waddstr and waddchstr use char* and chtype* parameters, respectively
waddwstr and wadd_chstr use wchar_t* and cchar_t* parameters.
Converting between the two forms can be a nuisance, because X/Open, etc., did not define functions for doing the conversion.
The manual page for bkgd describes how these video attributes are combined with the background character to obtain the actual display.
The accepted answer (by Mr. Dickey) is correct. However, the "ch" functions do not work with ordinary C strings (array of bytes). Another solution is to create a wrapper for waddstr which checks the current cursor position and window size and prints only as much as would fit.
For example:
int waddstr_trunc(WINDOW *win, const char *str)
{
int cur_x, max_x, dummy [[maybe_unused]];
getyx(win, dummy, cur_x);
getmaxyx(win, dummy, max_x);
int w=max_x - cur_x;
if (w <= 0) return 0;
char *str2 = strndup(str, w);
if (str2 == NULL) return 1;
int rv = waddstr(win, str2);
free(str2);
return rv;
}