Created
December 18, 2015 10:20
-
-
Save povder/ff6c66df57e04af652e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package wcatest | |
| import org.scalajs.dom | |
| import org.scalajs.dom.crypto.{CryptoKey, _} | |
| import org.scalajs.dom.raw.Promise | |
| import scala.concurrent.Future | |
| import scala.scalajs.concurrent.JSExecutionContext.Implicits.runNow | |
| import scala.scalajs.js | |
| import scala.scalajs.js.JSApp | |
| import scala.scalajs.js.JSConverters._ | |
| import scala.scalajs.js.annotation.JSExport | |
| import scala.scalajs.js.typedarray.{ArrayBuffer, Int8Array} | |
| @JSExport | |
| object WcaTest extends JSApp { | |
| @JSExport | |
| override def main(): Unit = { | |
| val rawKey = Array.fill(32)(1.toByte) | |
| val aesKeyAlgorithmId = AesKeyAlgorithm("AES-GCM", 256.toShort) | |
| val keyFuture: Future[js.Any] = dom.crypto.crypto.subtle.importKey(KeyFormat.raw, new Int8Array(rawKey.toJSArray), aesKeyAlgorithmId, extractable = false, js.Array(KeyUsage.encrypt, KeyUsage.decrypt)) | |
| keyFuture.flatMap { key => | |
| val cryptoKey = key.asInstanceOf[CryptoKey] | |
| val iv = new Int8Array(32) | |
| dom.crypto.crypto.getRandomValues(iv) | |
| val aesGcmParams = AesGcmParams(name = "AES-GCM", iv = iv, additionalData = new Int8Array(0), tagLength = 128.toShort) | |
| val cleartext = "secret" | |
| println(s"cleartext = $cleartext") | |
| val cleartextBytes = cleartext.getBytes("UTF-8") | |
| val ciphertextFuture = dom.crypto.crypto.subtle.encrypt(aesGcmParams, cryptoKey, new Int8Array(cleartextBytes.toJSArray)) | |
| ciphertextFuture.flatMap { ciphertextAny => | |
| val ciphertext = new Int8Array(ciphertextAny.asInstanceOf[ArrayBuffer]) | |
| println(s"ciphertext = ${ciphertext.toArray.mkString(",")}") | |
| val cleartextFuture: Future[js.Any] = dom.crypto.crypto.subtle.decrypt(aesGcmParams, cryptoKey, ciphertext) | |
| cleartextFuture.map { cleartextAny => | |
| val cleartext = new Int8Array(cleartextAny.asInstanceOf[ArrayBuffer]) | |
| val cleartextStr = new String(cleartext.toArray, "UTF-8") | |
| println(s"decrypted = $cleartextStr") | |
| } | |
| } | |
| }.recover { | |
| case t: Throwable => t.printStackTrace() | |
| } | |
| } | |
| implicit def promise2future[A](jsPromise: Promise[A]): Future[A] = { | |
| val p = concurrent.Promise[A] | |
| def onFulfilled(value: A) = p.success(value) | |
| def onRejected(reason: Any) = p.failure(new Exception("Promise rejected: " + reason.toString)) | |
| jsPromise.andThen(onFulfilled _, onRejected _) | |
| p.future | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment