Does slowAES allow/support zero padding? - javascript

I'm trying to perform AES encryption in CBC mode with zero padding. Does anyone know if aesSlow supports zero padding? Based on my reading of the code it doesn't and if that's the case; can anyone tell me why?
I'm using a 3rd party API which requires this encryption method.
jsfiddle.net/NMATS/2 is my current POC. I'll bemoving it to node once it's debugged. Also the inputs are similar but different for security.
Cheers,
Denis

It looks like you are correct. It appears to use PKCS7. Your options then are:
Pad it with 0's yourself and discard the last block of ciphertext
Edit the code and make the padding function do zero-padding (beware of license restrictions - I didn't look at the license)
As to why, I'd guess they just haven't had a need to do it or the time to implement it yet.
If you go with option 1, PKCS7 adds a full block of 0x10 bytes if your plaintext is already the multiple of a block size. Therefore, you can just pad your plaintext with 0x00 bytes to make it a multiple of a block size and encrypt it. Then you would drop the last 128-bits of the ciphertext (which is just 16 bytes of 0xFF encrypted). You will end up with a compatible result.
If you go with option 2, I'm not sure which implementation you are using, but I think they're all simple enough.
Here is the padding function for the Javascript implementation:
padBytesIn: function(data) {
var len = data.length;
var padByte = 16 - (len % 16);
for (var i = 0; i < padByte; i++) {
data.push(padByte);
}
},
Here is what you would change it to:
padBytesIn: function(data) {
var len = data.length;
if( len % 16 > 0 ){
var padLen = 16 - (len % 16);
for (var i = 0; i < padLen; i++) {
data.push(0);
}
}
},

Related

Different blowfish encryption results

I am trying to replicate a particular function from our SAP system to a web site and a part of the flow is a blowfish encryption. I looked around for Blowfish encryption libraries for Javascript and implemented it into my js code.
However, upon comparison with the original SAP flow, the results of our blowfish encryptions are different.
The only thing that's different is that SAP blowfish uses UTF-16LE. I've tried converting my password and the text to UTF-16LE but I cannot get the same results from the original system.
I've found these two codes while searching around (these 2 converts/decodes from UTF8-UTF16 and vice versa)
function strEncodeUTF16(str) {
var byteArray = new Uint8Array(str.length * 2);
for (var i = 0; i < str.length; i++) {
byteArray[i*2] = str.charCodeAt(i); // & 0xff;
byteArray[i*2+1] = str.charCodeAt(i) >> 8; // & 0xff;
}
return String.fromCharCode.apply(String,byteArray);
}
function decodeUTF16LE( binaryStr ) {
var cp = [];
for( var i = 0; i < binaryStr.length; i+=2) {
cp.push(
binaryStr.charCodeAt(i) |
( binaryStr.charCodeAt(i+1) << 8 )
);
}
return String.fromCharCode.apply( String, cp );
}
The blowfish library I'm using is from the Dojo Toolkit:
Blowfish.js from Dojo Toolkit 1.8.1
A sample test case would be:
Password: 7F30742A2
Text: 329
Result: B33663DFAC049492
However, when I try it on my end
var encrypted = blowfish.encrypt(id, key, {outputType:1, cipherMode: 0});
My result is:
ef701b0e904b10c3
I am not sure where the difference is happening. Any thoughts?

Twitter text js , not calculating the length from text which contains urls with #!

I am using Twitter text js to calculate length of text with urls containing #!.
eg:
"Some text http://domain.com#!/path/p/56319216 #tag1 #tag2".
In firefox debugger error generates on this line in twitter text js
twttr.txt.regexen.extractUrl.exec(text);
No specific error is logged instead my page freezes and alert me to stop the script, please help.
A pull request as been merged on the github repository on 2012-05-31 introducing the twttr.txt.getTweetLength(text, options) function that is taking consideration to t.co URLs and defined as follow :
twttr.txt.getTweetLength = function(text, options) {
if (!options) {
options = {
short_url_length: 22,
short_url_length_https: 23
};
}
var textLength = text.length;
var urlsWithIndices = twttr.txt.extractUrlsWithIndices(text);
for (var i = 0; i < urlsWithIndices.length; i++) {
// Subtract the length of the original URL
textLength += urlsWithIndices[i].indices[0] -urlsWithIndices[i].indices[1];
// Add 21 characters for URL starting with https://
// Otherwise add 20 characters
if (urlsWithIndices[i].url.toLowerCase().match(/^https:\/\//)) {
textLength += options.short_url_length_https;
} else {
textLength += options.short_url_length;
}
}
return textLength;
};
So your function will just become :
function charactersleft(tweet) {
return 140 - twttr.txt.getTweetLength(tweet);
}
Plus, regarding the best practices with t.co we should retrieve the short_url_length and short_url_length_https values from twitter and pass them as the options parameter in the twttr.txt.getTweetLength function :
Request GET help/configuration once daily in your application and cache the "short_url_length" (t.co's current maximum length value) for 24 hours. Cache "short_url_length_https" (the maximum length for HTTPS-based t.co links) and use it as the length of HTTPS-based URLs.
Especially knowing that some changes in the t.co urls length will be effective on 2013-02-20 as described in the twitter developer blog

How to load an Array (of numbers) into a google app script Byte[]

I have an Array (of numbers) in Google Apps Script, and I want to convert it to base64. I could of course use a simple open-source library such as this one.
However GAS already provides functions for this using Utilities.base64Encode(Byte[])
but to call this function I need a Byte[] not Number[].
Therefore the following script gives an error: (Cannot convert Array to (class)[].)
function testBase64Encode()
{
var bytes = [];
for (var i = 0; i < 255; i++) bytes.push(i);
var x = Utilities.base64Encode(bytes)
}
Normally Byte[]'s come directly out of a Blob's GetBytes() function, however in my case the Array (of numbers) comes out of zlib encryption lib.
So I am trying to find a way to convert that Number Array to a Byte[], acceptable for use with Utilities.base64Encode(Byte[]).
I did try to create a Byte myself and put them into an Array, however the following code also gives an error: (ReferenceError: "Byte" is not defined.)
var b1 = new Byte();
I did some more testing, and it seems to work as long as the value in the bytes' numeric values are 128 or lower. I find this weird because a byte should go up to 255.
The following code runs fine for 'bytes' but fails for 'bytes2' because there is a value greater than 128:
function testByteArrays()
{
var bytes = [];
for (var i = 0; i < 128; i++) bytes.push(i);
var x = Utilities.newBlob(bytes)
var bytes2 = [];
for (var i = 0; i < 129; i++) bytes2.push(i);
var x = Utilities.newBlob(bytes2)
}
...a byte should go up to 255.
But not in Two's complement notation... in that case, the bytes should be in the range [-128..127], where the high-order bit is reserved as a sign bit. Given a positive integer i, we need to calculate the two's complement if it is greater than 127. That can be done by subtracting 28 (256). Applying that to your first example:
function testBase64Encode()
{
var bytes = [];
for (var i = 0; i < 255; i++) bytes.push(i<128?i:i-256);
var x = Utilities.base64Encode(bytes)
}
This will avoid the error message you were receiving (Cannot convert Array to (class)[].). Ideally, you should also ensure that the number values start in the range 0..255.

LESS CSS with custom javascript function for cookieless domain

I'd like to use less ( http://lesscss.org/ ) instead of sass ( http://sass-lang.com/ ) for preprocessing css. I have a set of cookieless domains for static resources. For example: 0.mydomain.com, 1.mydomain.com, 2.mydomain.com, etc. I would like to compile CSS using less such that the cookieless domains are injected into the compiled CSS output. I found this ability to to create custom functions in the sass docs using #function. Does the equivalent exist for less (I can not find)? I need a function that performs a hashing algorithm to convert a filename into a number X corresponding to a cookieless domain (X.mydomain.com). How would one do this using less?
The below example is contrived for illustration:
In my.less file:
#function domainX(path) {
//configs
var protocol = "http://";
var domain = ".mydomain.com"
var N = 4; //4 cookieless domains
var sum = 0;
var s = path.substr(path.lastIndexOf("/") + 1);
for (var i = 0; i < s.length; i++) {
sum += s[i].charCodeAt();
}
#return protocol + (sum % N) + domain + path;
}
.myItem {background-image:url(domainX('/images/background.jpg')) }
that would generate compiled output
.myItem {background-image:url('http://1.mydomain.com/images/background.jpg') }
The SASS example is
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#functions
See section "Function Directives"
The closest example from the LESS docs is below, but there's no function to construct the base-url.
#base-url: "http://assets.fnord.com";
background-image: url("#{base-url}/images/bg.png");
Maybe there is a LESS + Node.js part of the solution too?
Thanks!
You should be able to do this using LeSS' ability to embed js:
.background(#path) {
background-image: ~`(function(){ var protocol = "http://"; var domain = ".mydomain.com"; var N = 4; var sum = 0; var s = #{path}.substr(#{path}.lastIndexOf("/") + 1); for (var i = 0; i < s.length; i++) { sum += s[i].charCodeAt(); } return "url(" + protocol + (sum % N) + domain + #{path} + ")";})()`;
}
.myItem {
.background("/images/background.jpg");
}
no idea what the performance would be like, but then if you're processing server side you won't care, and client side it caches so shouldn't be a problem.
No. LESS has considerably less features than Sass (no functions, no loops). You would have to use a mixin to do anything remotely like that. Sass could do it except for the fact that it doesn't have any string manipulation functions built in, so you'd have to write a bit of Ruby code to add those in.

Split an IP address into Octets, then do some math on each of the Octets

I actually have this working, but its very ugly, and its keeping me awake at night trying to come up with an eloquent piece of code to accomplish it.
I need to take a series of strings representing IP Ranges and determine how many actual IP address that string would represent. My approach has been to split that into 4 octets, then attempt to split each octet and do the math from there.
e.g.: 1.2.3.4-6 represents 1.2.3.4, 1.2.3.5, and 1.2.3.6, thus I want to get the answer of 3 from this range.
To further complicate it, the string I'm starting with can be a list of such ranges from a text box, separated by newlines, so I need to look at each line individually, get the count of represented IP address, and finally, how many of the submitted ranges have this condition.
1.1.1.4-6 /* Represents 3 actual IP Addresses, need to know "3" */
2.2.3-10.255 /* Represents 8 actual IP Addresses, need to know "8" */
3.3.3.3 /* No ranges specified, skip this
4.4.4.4 /* No ranges specified, skip this
Net result is that I want to know is that 2 lines contained a "range", which represent 8 IP addresses (3+8)
Any eloquent solutions would be appreciated by my sleep schedule. :
)
There you go:
var ips = ["1.2.3.4", "2.3.4-6.7", "1.2.3.4-12"];
for(var i=0; i<ips.length; i++) {
var num = 1;
var ip = ips[i];
var parts = ip.split('.');
for(var j=0; j<parts.length; j++) {
var part = parts[j];
if(/-/.test(part)) {
var range = part.split('-');
num *= parseInt(range[1]) - parseInt(range[0]) + 1;
}
}
alert(ip + " has " + num + " ips.");
}​
This code also handles ranges like 1.2.3-4.0-255 correctly (i.e. 256*2=512 ips in that range). The list items that have no ranges yield a total of 1 ips, and you can ignore them based on the resulting num if you don't need them.
You'll probably need to slightly modify my example, but I'm confident you won't have any trouble in doing so.
Ok, this is how I would do it
var addr = '1.1.3-10.4-6';
function getNumAddresses(input) {
var chunks = input.split('.');
var result = 1;
for (var i = 0; i < 4; i++) {
if (chunks[i].indexOf('-') != -1) {
var range = chunks[i].split('-');
result *= parseInt(range[1]) - parseInt(range[0]) + 1;
}
}
return result;
}
alert(getNumAddresses(addr));

Categories