Question

I'm currently experimenting with SJCL but I'm having trouble with encryption/decryption. With the lack of good examples I came up with what you see below but it's not working. Can anybody point out what I'm doing wrong? Thanks in advance.

<html>
<!-- sjcl made with: ./configure --with-all -compress=none && make  -->
<script type="text/javascript" src="sjcl.js"></script>
<body>

<script>
var p = {
  "iv": "PnWtrKCP2DKcLyNC18RKAw==",
  "ts": 128,
  "mode": "gcm",
  "adata": "You can read me",
  "cipher": "aes",
  "key": "QiJysyALRxUESl18XKl0FcpXQJvFB2Z3Q3A61tdNNM0="    // pbkdf2 key
};

var prp = new sjcl.cipher[p.cipher](sjcl.codec.base64.toBits(p.key));
var plain = "My plaintext";

var ct = sjcl.codec.base64.fromBits(sjcl.mode[p.mode].encrypt(prp, sjcl.codec.bytes.toBits(plain), p.iv, p.adata, p.ts));
var pt = sjcl.codec.base64.fromBits(sjcl.mode[p.mode].decrypt(prp, sjcl.codec.base64.toBits(ct),   p.iv, p.adata, p.ts));

document.writeln("ct: " + ct + "<br>");
document.writeln("pt: " + pt + "<br>");
</script>

<hr><pre> 
Results in:
encrypted: 5Z2QQ9s6gfORlr6qLvlwjO/J+/TbfSbOs79c4w==
decrypted: AAAAAAAAAAAAAAAA
</pre></body></html>
Était-ce utile?

La solution

I think your problem is sjcl.codec.bytes.toBits(plaintext). If you run that by itself, you get [0,0,0]. I think you want sjcl.codec.utf8String.toBits(plaintext) instead.

You would use bytes.toBits if you have an actual byte (octet) array (like [255, 34, 12, 16]), but in this case you're using a string so it needs to be converted differently.

Also, I've had problems with using strings for IVs, you may want to run it through the same conversion as the key before passing it in (base64.toBits(iv)).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top