java.security.NoSuchAlgorithmException Scala Examples

The following examples show how to use java.security.NoSuchAlgorithmException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Enigma.scala    From matcher   with MIT License 6 votes vote down vote up
package com.wavesplatform.dex.crypto

import java.nio.charset.StandardCharsets
import java.security.NoSuchAlgorithmException
import java.security.spec.InvalidKeySpecException

import javax.crypto.spec.{PBEKeySpec, SecretKeySpec}
import javax.crypto.{Cipher, SecretKeyFactory}

import scala.util.control.NonFatal

object Enigma {

  private[this] val KeySalt           = "0495c728-1614-41f6-8ac3-966c22b4a62d".getBytes(StandardCharsets.UTF_8)
  private[this] val AES               = "AES"
  private[this] val Algorithm         = AES + "/ECB/PKCS5Padding"
  private[this] val HashingIterations = 999999
  private[this] val KeySizeBits       = 128

  def hashPassword(password: Array[Char],
                   salt: Array[Byte],
                   iterations: Int = HashingIterations,
                   keyLength: Int = KeySizeBits,
                   hashingAlgorithm: String = "PBKDF2WithHmacSHA512"): Array[Byte] =
    try {
      val keyFactory = SecretKeyFactory.getInstance(hashingAlgorithm)
      val keySpec    = new PBEKeySpec(password, salt, iterations, keyLength)
      val key        = keyFactory.generateSecret(keySpec)
      key.getEncoded
    } catch {
      case e @ (_: NoSuchAlgorithmException | _: InvalidKeySpecException) => throw new RuntimeException("Password hashing error", e)
    }

  def prepareDefaultKey(password: String): SecretKeySpec = new SecretKeySpec(hashPassword(password.toCharArray, KeySalt), AES)

  def encrypt(key: SecretKeySpec, bytes: Array[Byte]): Array[Byte] =
    try {
      val cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.ENCRYPT_MODE, key)
      cipher.doFinal(bytes)
    } catch {
      case NonFatal(e) => throw new RuntimeException("Encrypt error", e)
    }

  def decrypt(key: SecretKeySpec, encryptedBytes: Array[Byte]): Array[Byte] =
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.DECRYPT_MODE, key)
      cipher.doFinal(encryptedBytes)
    } catch {
      case NonFatal(e) => throw new RuntimeException("Decrypt error", e)
    }
} 
Example 2
Source File: HmacSpec.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.communication.security

import java.security.NoSuchAlgorithmException

import org.scalatest.{FunSpec, Matchers}

class HmacSpec extends FunSpec with Matchers {
  describe("Hmac Object") {
    describe("#apply") {
      it("should fail if the algorithm is not available") {
        val nonEmptyKey = "FILL"
        val badAlgorithm = "One day, I want to be a real algorithm"

        intercept[NoSuchAlgorithmException] {
          val hmac = Hmac(nonEmptyKey, HmacAlgorithm(badAlgorithm))
        }
      }

      it("should succeed if the algorithm is available") {
        val goodAlgorithm = HmacAlgorithm.SHA256

        val hmac = Hmac("", goodAlgorithm)
        hmac.algorithm should be (goodAlgorithm)
      }
    }

    describe("#newMD5") {
      it("should produce an Hmac with the algorithm set to MD5") {
        val hmac = Hmac.newMD5("")

        hmac.algorithm should be(HmacAlgorithm.MD5)
      }
    }

    describe("#newSHA1") {
      it("should produce an Hmac with the algorithm set to SHA1") {
        val hmac = Hmac.newSHA1("")

        hmac.algorithm should be(HmacAlgorithm.SHA1)
      }
    }

    describe("#newSHA256") {
      it("should produce an Hmac with the algorithm set to SHA256") {
        val hmac = Hmac.newSHA256("")

        hmac.algorithm should be(HmacAlgorithm.SHA256)
      }
    }
  }

  describe("Hmac Class") {
    describe("#apply") {
      // TODO: This should really be mocked since we don't care about the
      //       results, just the send/receive to the underlying implementation
      it("should produce the correct digest") {
        val key = "12345"
        val message = "This is a test of SHA256 in action."
        val expected =
          "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc"
        val hmac = new Hmac(key, HmacAlgorithm.SHA256)

        hmac(message) should be(expected)
      }
    }

    describe("#digest") {
      // TODO: This should really be mocked since we don't care about the
      //       results, just the send/receive to the underlying implementation
      it("should produce the correct digest") {
        val key = "12345"
        val message = List("This is a test of SHA256 in action.")
        val expected =
          "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc"
        val hmac = new Hmac(key, HmacAlgorithm.SHA256)

        hmac.digest(message) should be(expected)
      }
    }
  }

  describe("HmacAlgorithm") {
    describe("#apply") {
      it("should return a value wrapping the string input") {
        val resultTypeName = HmacAlgorithm("").getClass.getName

        // NOTE: Test written this way since unable to check directly against
        //       the Scala enumeration value
        resultTypeName should be ("scala.Enumeration$Val")
      }
    }
  }
} 
Example 3
Source File: HmacSpec.scala    From incubator-toree   with Apache License 2.0 5 votes vote down vote up
package org.apache.toree.communication.security

import java.security.NoSuchAlgorithmException

import org.scalatest.{FunSpec, Matchers}

class HmacSpec extends FunSpec with Matchers {
  describe("Hmac Object") {
    describe("#apply") {
      it("should fail if the algorithm is not available") {
        val nonEmptyKey = "FILL"
        val badAlgorithm = "One day, I want to be a real algorithm"

        intercept[NoSuchAlgorithmException] {
          val hmac = Hmac(nonEmptyKey, HmacAlgorithm(badAlgorithm))
        }
      }

      it("should succeed if the algorithm is available") {
        val goodAlgorithm = HmacAlgorithm.SHA256

        val hmac = Hmac("", goodAlgorithm)
        hmac.algorithm should be (goodAlgorithm)
      }
    }

    describe("#newMD5") {
      it("should produce an Hmac with the algorithm set to MD5") {
        val hmac = Hmac.newMD5("")

        hmac.algorithm should be(HmacAlgorithm.MD5)
      }
    }

    describe("#newSHA1") {
      it("should produce an Hmac with the algorithm set to SHA1") {
        val hmac = Hmac.newSHA1("")

        hmac.algorithm should be(HmacAlgorithm.SHA1)
      }
    }

    describe("#newSHA256") {
      it("should produce an Hmac with the algorithm set to SHA256") {
        val hmac = Hmac.newSHA256("")

        hmac.algorithm should be(HmacAlgorithm.SHA256)
      }
    }
  }

  describe("Hmac Class") {
    describe("#apply") {
      // TODO: This should really be mocked since we don't care about the
      //       results, just the send/receive to the underlying implementation
      it("should produce the correct digest") {
        val key = "12345"
        val message = "This is a test of SHA256 in action."
        val expected =
          "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc"
        val hmac = new Hmac(key, HmacAlgorithm.SHA256)

        hmac(message) should be(expected)
      }
    }

    describe("#digest") {
      // TODO: This should really be mocked since we don't care about the
      //       results, just the send/receive to the underlying implementation
      it("should produce the correct digest") {
        val key = "12345"
        val message = List("This is a test of SHA256 in action.")
        val expected =
          "e60e1494b0650875fa5eb8384e357d731358c3559c1f223d69dc43ffe13570bc"
        val hmac = new Hmac(key, HmacAlgorithm.SHA256)

        hmac.digest(message) should be(expected)
      }
    }
  }

  describe("HmacAlgorithm") {
    describe("#apply") {
      it("should return a value wrapping the string input") {
        val resultTypeName = HmacAlgorithm("").getClass.getName

        // NOTE: Test written this way since unable to check directly against
        //       the Scala enumeration value
        resultTypeName should be ("scala.Enumeration$Val")
      }
    }
  }
} 
Example 4
Source File: JsonFileStorage.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.utils

import java.io.{File, PrintWriter}

import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import play.api.libs.json.{Json, Reads, Writes}
import java.util.Base64

import scala.io.Source
import scala.util.control.NonFatal

object JsonFileStorage {
  private[this] val KeySalt           = "0495c728-1614-41f6-8ac3-966c22b4a62d"
  private[this] val AES               = "AES"
  private[this] val Algorithm         = AES + "/ECB/PKCS5Padding"
  private[this] val HashingAlgorithm  = "PBKDF2WithHmacSHA512"
  private[this] val HashingIterations = 999999
  private[this] val KeySizeBits       = 128

  def prepareKey(key: String): SecretKeySpec = {
    import java.security.NoSuchAlgorithmException
    import java.security.spec.InvalidKeySpecException

    import javax.crypto.SecretKeyFactory
    import javax.crypto.spec.PBEKeySpec

    def hashPassword(password: Array[Char], salt: Array[Byte], iterations: Int, keyLength: Int): Array[Byte] =
      try {
        val keyFactory = SecretKeyFactory.getInstance(HashingAlgorithm)
        val keySpec    = new PBEKeySpec(password, salt, iterations, keyLength)
        val key        = keyFactory.generateSecret(keySpec)
        key.getEncoded
      } catch {
        case e @ (_: NoSuchAlgorithmException | _: InvalidKeySpecException) =>
          throw new RuntimeException("Password hashing error", e)
      }

    new SecretKeySpec(hashPassword(key.toCharArray, KeySalt.utf8Bytes, HashingIterations, KeySizeBits), AES)
  }

  def save[T](value: T, path: String, key: Option[SecretKeySpec])(implicit w: Writes[T]): Unit = {
    val folder = new File(path).getParentFile
    if (!folder.exists()) folder.mkdirs()

    val file = new PrintWriter(path)
    try {
      val json = Json.toJson(value).toString()
      val data = key.fold(json)(k => encrypt(k, json))
      file.write(data)
    } finally file.close()
  }

  def save[T](value: T, path: String)(implicit w: Writes[T]): Unit =
    save(value, path, None)

  def load[T](path: String, key: Option[SecretKeySpec] = None)(implicit r: Reads[T]): T = {
    val file = Source.fromFile(path)
    try {
      val dataStr = file.mkString
      Json.parse(key.fold(dataStr)(k => decrypt(k, dataStr))).as[T]
    } finally file.close()
  }

  def load[T](path: String)(implicit r: Reads[T]): T =
    load(path, Option.empty[SecretKeySpec])(r)

  private[this] def encrypt(key: SecretKeySpec, value: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.ENCRYPT_MODE, key)
      new String(Base64.getEncoder.encode(cipher.doFinal(value.utf8Bytes)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage encrypt error", e)
    }
  }

  private[this] def decrypt(key: SecretKeySpec, encryptedValue: String): String = {
    try {
      val cipher: Cipher = Cipher.getInstance(Algorithm)
      cipher.init(Cipher.DECRYPT_MODE, key)
      new String(cipher.doFinal(Base64.getDecoder.decode(encryptedValue)))
    } catch {
      case NonFatal(e) =>
        throw new RuntimeException("File storage decrypt error", e)
    }
  }
}