beatgammit / base64-js Goto Github PK
View Code? Open in Web Editor NEWBase64 encoding/decoding in pure JS
License: MIT License
Base64 encoding/decoding in pure JS
License: MIT License
@beatgammit, @feross: I see that this package now has an MIT license, but also that it was originally derived (extracted?) from deflate-js, which is GPLv2. Any way to confirm that this base64-js code is not derived from GPLv2 deflate code?
Hi, the incorrect repo is specified in the package.json:
https://github.com/beatgammit/base64-js/blob/master/package.json#L8
Also, there's no license specified in this project which causes a lot of ambiguity. I see that most of your other projects are GPLv2. I can only beg and plead that you consider licensing this MIT to be compatible with the existing dependencies that depend on this project. Please :) .
This is related to these issues
browserify/browserify#488
toots/buffer-browserify#29
[email protected]
use const
keyword:
const lookup = []
compile to es5 has error.
The keyword 'const' is reserved
For example, the data [0, 1, -1] serialise to AAD/ but should be AAH/ and [ 0, -73, 23] serialise to /7cX but should be ALcX.
I was trying to encode some relatively large audio data (32meg?). Calling uint8ToBase64
crashed my browser. I changed the code to this
var parts = [];
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
if (output.length > 16384) {
parts.push(output)
output = ''
}
}
...
parts.push(output);
return parts.join('');
What do you think? I don't know what a good chunk size is but I'm sure you know each time you do output +=
something JavaScript is probably allocating a string, copying the old string into it followed by whatever your appending. That means it should get progressively slower as output gets longer.
In any case I just thought I'd pass this along of it helps others. It doesn't make a whole lot of sense to me that Chrome would crash from this. I'd just expect a GC hiccup at worst. On the other hand the giant output string ends up allocating lots of giant strings toward the end whereas chunkifying it means only the last join make a giant string. I suppose this is voodoo code.
Hi - looking to pick up and use this library if possible because we are looking to massively optimise this part of our code.
However I have a question about the number of object allocations and function calls that are made in a call to either toByteArray
or fromByteArray
Consider the following Base64 string (taken from here):
let s = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
A call to base64.toByteArray
results in 629 function calls.
Calling base64.fromByteArray
on the result of the previous call results in 450 function calls.
Unless one's Javascript runtime is inlining all of these function calls there is going to be an overhead for each one (I'm not sure to what extent Javascript VMs have evolved...?)
encode
for example is called 360 times; this is simply accessing an object.
Many of these calls could simply be inlined 'by hand' so as not to rely on the Javascript VM (which may vary between browsers etc)
Has this been explored at all?
Are there any performance tests which would help to benchmark the significance of any such changes?
Thanks
as the title
Looks like the version in bower.json is still 1.0.0, which causes this warning when installing:
$ bower install --save base64-js
bower base64-js#* not-cached https://github.com/beatgammit/base64-js.git#*
bower base64-js#* resolve https://github.com/beatgammit/base64-js.git#*
bower base64-js#* checkout v1.1.2
bower base64-js#* mismatch Version declared in the json (1.0.0) is different than the resolved one (1.1.2)
bower base64-js#* resolved https://github.com/beatgammit/base64-js.git#1.1.2
bower base64-js#^1.1.2 install base64-js#1.1.2
when a base64 encoded string is input to this function it is producing a Arraybuffer which internally changes its original value. If we again convert the array buffer to base64 then a different base64 is generated. Hence When i am trying to implement signature verification for a hybrid app, then the digest value is getting differ and hence a mismatch between front-end and back-end.
Need an urgent help please. We are stuck at client project delivery. Earnest request.
Code
const base64String = 'ewogICJhIiA6ICIxIgp9';
var base64js = require('base64-js');
const arrayBuffer = base64js.toByteArray(base64String).buffer;
console.log('==============');
console.log(arrayBuffer);
console.log('==============');
In React-native
Print:
==============
[]
==============
package.json:
"dependencies": {
"base64-js": "^1.5.1",
"react": "18.2.0",
"react-native": "0.72.4"
},
I am trying to create a new node project,Decode properly.
In new project
Print:
==============
ArrayBuffer {
[Uint8Contents]: <7b 0a 20 20 22 61 22 20 3a 20 22 31 22 0a 7d>,
byteLength: 15
}
==============
package.json:
"dependencies": {
"base64-js": "^1.5.1"
},
Node:
version: 20.5.0
I don't know what went wrong that led to this result. Is there any way to solve it?
is it?
I am having trouble to understand how to use base64-js in a webbrowser, where no require is available.
The methods byteLength
/toByteArray
/fromByteArray
are not available globally when adding <script src="js/base64-js-1.2.0/index.js"></script>
to my site.
The only hack I found to use it was to change
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
into
var base64js_byteLength = byteLength
var base64js_toByteArray = toByteArray
var base64js_fromByteArray = fromByteArray
What is the itended way to do this? Could this be added to the readme? Thanks a lot!
How import this in react native?
const base64 = require('base-64');
Module does not exist in the module map or in these directories
not added to package.JSON but there base64 folder in node modules.
This library would be much easier to use if it handled strings directly.
The "buffer" npm library has webpack usage issues.
If you have an easy way to convert strings to the right kind of array (in the browser which doesn't have built in Buffer library like Node) that would make this library much easier to use in the Browser.
Hello,
Quoting the comment of the commit :
if folks miss the ability to drop this into the browser, open an issue and we’ll add a built file to the repo
What was the main reason to remove the self executing function, which prevents adding variables to the global scope ? Should we encapsulate the file in a function to use it in a browser ?
Line 17 in be644de
I'm just curious on this one. Is there a js environment that doesn't implement that?
The library doesn't support decoding concatenated base64 files because it doesn't handle padding characters correctly when they are not located at the end of the stream.
For example, 'SQ==QU0=' should decode to [73,65,77] but it decodes to [73,0,0,65,77].
I have modfied the convert.js tests to show the problem in this patch base64-concat.txt.
While on my Chrome console, I copy-pasted the base64js.min.js,
called base64.js.toByteArray on my copy-pasted data from file and obtained the beautiful Uint32Array [5722] I expected,
This simple node script crashes with that same data,
var fs = require('fs')
var base64js = require('base64-js')
fs.readFile('./test', (err, data) => {
if (err) throw err;
// var byteArray = base64js.toByteArray(data) // crashes at index.js:70:22
console.log(base64js.byteLength(data)) // returns successfully 5722
})
I tried every encoding for the file without any change, and the file is successfully parsed by a C# .NET Convert.FromBase64String(File.ReadAllText( call.
Anyone has an idea?
otherwise the decoded result is not correct or not possible.
Hi,
Just ran this projects index.js
file through the TypeScript compiler, and its flagged up an issue with respect to toByteArray
function. This function is using the indexer i
to b64.charCodeAt(i)
but i
is not in scope (it is used in an iteration above however).
https://github.com/beatgammit/base64-js/blob/master/index.js#L79-L93
Can be tripped if (placeHoldersLen === 2)
or (placeHoldersLen === 1)
evaluate true
How to reproduce
base64js.toByteArray("====")
Expected
An empty string
Actual
Exception is thrown "Invalid typed array length: -1"
A valid base64 input length including characters not in the base64 alphabet lead to wrong outputs instead of an exception. E.g.
$ node
> var base64js = require('base64-js')
> base64js.toByteArray("aaaä")
Uint8Array [ 105, 166, 128 ]
> base64js.toByteArray("aaa}")
Uint8Array [ 105, 166, 128 ]
ver. 1.3.0 and master.
<script>
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var icon = base64js.fromByteArray(this.response);
alert(icon); // Empty string
}
xhr.open('GET', 'symbols/icon.png', true);
xhr.send();
</script>
What's wrong with this example?
This would avoid it becoming an accidental global if this file were to be concatenated with others or included directly onto an HTML page.
I just stumbled upon the problem that the fromByteArray
function sometimes seems to return a broken base64 encoded string that contains undefined
.
The Int8Array
I'm using here is the result of a sha256 hash of a string.
Here is an example to reproduce:
fromByteArray(new Int8Array([90, 37, 97, -101, 96, -81, 13, 14, -74, -110, 100, -47, -76, -82, -80, -11, 96, 34, -93, 44, -31, 72, -121, 101, -6, -43, -24, -67, 61, -101, -113, 83]))
Yields:
"WiVhm2CvDQ62kmTRtK6w9WAioyzhSIdl+tXovT2bundefined1M="
The correct result would be:
"WiVhm2CvDQ62kmTRtK6w9WAioyzhSIdl+tXovT2bj1M"
So it seems that the j
is not encoded properly...?
The two bytes -101, -113
at end of Int8Array
seems to cause the problem.
Considering this package has essentially had no activity for over 3 years, I am willing to take over maintainership/ownership of it. We are using this library in the Keycloak project, specifically for our Keycloak JS adapter here at Red Hat.
I would specifically take the following actions:
Please publish a new version on npm.
import b64 from 'base64-js'
import { ImagePicker } from 'expo'
_pickImageFromGallery = async () => {
const image = await ImagePicker.launchImageLibraryAsync({ allowsEditing: false, base64: true })
const byteArray = await b64.toByteArray(image.base64)
}
//result: [Unhandled promise rejection: Error: Invalid string. Length must be a multiple of 4]
After 4 days fiddleing wit build in base 64 and thinkig about a psyhologist
it helps me really out :)
I was ajax fetching images as binary and want to have a base64 string of the data. Nothing was working it just blew up.
This helps.
var bin = new Uint8Array(FILES[file].data);
FILES[file].data=bin
var b64= fromByteArray(bin)
:)
Can you set these up so we get continuous testing?
Strictly speaking the '=' characters do not carry any information. Can decode ignore missing padding and not throw an error?
Hello downvoters, care to explain your reasoning?
I already ran this
bower register base64-js https://github.com/beatgammit/base64-js
But you need to accept the pull request and also you'll need to run
git clone [email protected]:beatgammit/base64-js.git
pushd base64-js
git tag v1.0.0
git push --tags
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.