• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala BCrypt类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.mindrot.jbcrypt.BCrypt的典型用法代码示例。如果您正苦于以下问题:Scala BCrypt类的具体用法?Scala BCrypt怎么用?Scala BCrypt使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了BCrypt类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: AddUserRequest

//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Users
import org.mindrot.jbcrypt.BCrypt

import scala.util.Try


case class AddUserRequest(
                         email: String,
                         name: String,
                         password: String
) {
  def toUser: Try[Users] = Try {
    Users(
      id = None,
      email = email,
      name = name,
      password = BCrypt.hashpw(password, BCrypt.gensalt(12))
    )
  }
} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:22,代码来源:AddUserRequest.scala


示例2: User

//设置package包名称以及导入依赖的类
package models

import org.joda.time.LocalDateTime
import org.mindrot.jbcrypt.BCrypt


class User private (
  val id: Long,
  val name: String,
  val email: String,
  val passwordDigest: String,
  val createdAt: LocalDateTime,
  val updatedAt: LocalDateTime
) {

  def verifyPassword(password: String): Boolean = {
    BCrypt.checkpw(password, passwordDigest)
  }
}

object User {
  def apply(
    id: Long,
    name: String,
    email: String,
    passwordDigest: String,
    createdAt: LocalDateTime = LocalDateTime.now,
    updatedAt: LocalDateTime = LocalDateTime.now
  ): User = {
    val validName = name match {
      case n if n.length > 50 => throw new Exception
      case _ => name
    }
    val validEmail = email match {
      case e if e.length > 255 => throw new Exception
      case e if !e.matches("""\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z""") => throw new Exception
      case _ => email
    }
    val validPass = passwordDigest match {
      case pass if pass.length < 6 => throw new Exception
      case _ => passwordDigest
    }

    new User(id = id, name = validName, email = validEmail, passwordDigest = validPass, createdAt = createdAt, updatedAt = updatedAt)
  }
} 
开发者ID:benevolent0505,项目名称:My-PlayFramework-Sample,代码行数:47,代码来源:User.scala


示例3: PasswordHash

//设置package包名称以及导入依赖的类
package controllers.model

import org.mindrot.jbcrypt.BCrypt

class PasswordHash(val pwHash: String) {
  def compare(password: String): Boolean = BCrypt.checkpw(password, pwHash)
}

object Password {
  def apply(password: String) = {
    val pwHash = BCrypt.hashpw(password, BCrypt.gensalt())
    new PasswordHash(pwHash)
  }
}

object PasswordHash {
  def apply(passwordHash: String) = new PasswordHash(passwordHash)
} 
开发者ID:omefire,项目名称:Scodex,代码行数:19,代码来源:Password.scala


示例4: AuthService

//设置package包名称以及导入依赖的类
package services

import java.security.MessageDigest
import java.util.UUID
import java.util.concurrent.TimeUnit

import model.User
import org.apache.commons.codec.binary.Base64
import org.mindrot.jbcrypt.BCrypt
import play.api.cache.SyncCacheApi
import play.api.mvc.{Cookie, RequestHeader}
import scalikejdbc._

import scala.concurrent.duration.Duration


class AuthService(cacheApi: SyncCacheApi) {

  def login(userCode: String, password: String): Option[Cookie] = {
    for {
      user <- checkUser(userCode, password)
      cookie <- Some(createCookie(user))
    } yield {
      cookie
    }
  }

  def checkCookie(header: RequestHeader): Option[User] = {
    for {
      cookie <- header.cookies.get(cookieHeader)
      user <- cacheApi.get[User](cookie.value)
    } yield {
      user
    }
  }

  private def checkUser(userCode: String, password: String): Option[User] =
    DB.readOnly { implicit session =>
    val maybeUser = sql"select * from users where user_code = $userCode".
      map(User.fromRS).single().apply()
    maybeUser.flatMap { user =>
      if (BCrypt.checkpw(password, user.password)) {
        Some(user)
      } else None
    }
  }

  val mda = MessageDigest.getInstance("SHA-512")
  val cookieHeader = "X-Auth-Token"

  private def createCookie(user: User): Cookie = {
    val randomPart = UUID.randomUUID().toString.toUpperCase
    val userPart = user.userId.toString.toUpperCase
    val key = s"$randomPart|$userPart"
    val token = Base64.encodeBase64String(mda.digest(key.getBytes))
    val duration = Duration.create(10, TimeUnit.HOURS)
    cacheApi.set(token, user, duration)
    Cookie(cookieHeader, token, maxAge = Some(duration.toSeconds.toInt))
  }
} 
开发者ID:denisftw,项目名称:modern-web-scala,代码行数:61,代码来源:AuthService.scala


示例5: authenticate

//设置package包名称以及导入依赖的类
package services

import javax.inject.Inject

import org.mindrot.jbcrypt.BCrypt
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.BSONObjectID
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}


trait AuthService {
  def authenticate(email:String,password:String)(implicit ec: ExecutionContext):Future[Option[String]]
}



class MongoAuthService @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends AuthService {

  val collection = "users"

  override def authenticate(email: String, password: String)(implicit ec: ExecutionContext): Future[Option[String]] = {
    for {
      users <- reactiveMongoApi.database.map(_.collection[JSONCollection](collection))
      userOpt  <- users.find(Json.obj("email"->email)).one[JsObject]
      authenticated <- userOpt.map { user =>
        Future.successful(BCrypt.checkpw(password,(user \ "password").as[String]))
      }.getOrElse(Future.successful(false))
      id <- (userOpt,authenticated) match {
        case (Some(user),true) =>
          val _id:String= (user \ "_id").as[BSONObjectID].stringify
          Future.successful(Some(_id))
        case (None,_) =>  Future.successful(None)
        case (_,false) => Future.successful(None)
      }
    } yield id
  }
} 
开发者ID:sdor,项目名称:labnotes-server,代码行数:42,代码来源:AuthService.scala


示例6: AuthUtil

//设置package包名称以及导入依赖的类
package util

import models.User
import org.mindrot.jbcrypt.BCrypt

object AuthUtil {

    def authenticate(username: String, password: String): Option[User] = {
        val user = User.find(username)
        if (user.isDefined)
            if (BCrypt.checkpw(password, user.get.password))
                user
            else
                None
        else
            None
    }

} 
开发者ID:Cobbleopolis,项目名称:Promptiosaurus,代码行数:20,代码来源:AuthUtil.scala


示例7: SheepEntity

//设置package包名称以及导入依赖的类
package me.archdev.restapi.models

import org.mindrot.jbcrypt.BCrypt

case class SheepEntity(id: Option[Long] = None, sheepname: String, password: String) {
  require(!sheepname.isEmpty, "sheepname.empty")
  require(!password.isEmpty, "password.empty")

  def withHashedPassword(): SheepEntity = this.copy(password = BCrypt.hashpw(password, BCrypt.gensalt()))
}

case class SheepEntityUpdate(sheepname: Option[String] = None, password: Option[String] = None) {
  def merge(sheep: SheepEntity): SheepEntity = {
    SheepEntity(sheep.id, sheepname.getOrElse(sheep.sheepname), password.map(ps => BCrypt.hashpw(ps, BCrypt.gensalt())).getOrElse(sheep.password))
  }
} 
开发者ID:samuelmartingc,项目名称:Akka-REST-service,代码行数:17,代码来源:SheepEntity.scala


示例8: UserEntity

//设置package包名称以及导入依赖的类
package me.archdev.restapi.models

import org.mindrot.jbcrypt.BCrypt

case class UserEntity(id: Option[Long] = None, username: String, password: String) {
  require(!username.isEmpty, "username.empty")
  require(!password.isEmpty, "password.empty")

  def withHashedPassword(): UserEntity = this.copy(password = BCrypt.hashpw(password, BCrypt.gensalt()))
}

case class UserEntityUpdate(username: Option[String] = None, password: Option[String] = None) {
  def merge(user: UserEntity): UserEntity = {
    UserEntity(user.id, username.getOrElse(user.username), password.map(ps => BCrypt.hashpw(ps, BCrypt.gensalt())).getOrElse(user.password))
  }
} 
开发者ID:samuelmartingc,项目名称:Akka-REST-service,代码行数:17,代码来源:UserEntity.scala


示例9: UserDao

//设置package包名称以及导入依赖的类
package dao

import java.util.UUID

import model.User
import org.mindrot.jbcrypt.BCrypt
import scalikejdbc._

import scala.util.Try


class UserDao {

  def findById(userId: UUID): Try[Option[User]] = Try {
    NamedDB('auth).readOnly { implicit session =>
      sql"select * from users where user_id = $userId".
        map(User.fromRS).headOption().apply()
    }
  }

  def getUsers: Try[Seq[User]] = Try {
    NamedDB('auth).readOnly { implicit session =>
      sql"select * from users".map(User.fromRS).list().apply()
    }
  }

  def insertUser(userCode: String, fullName: String,
    password: String): Try[User] = Try {
    val passwordHash = BCrypt.hashpw(password, BCrypt.gensalt())
    val user = User(UUID.randomUUID(), userCode, fullName, passwordHash, isAdmin = false)
    NamedDB('auth).localTx { implicit session =>
      sql"""insert into users(user_id, user_code, full_name, password, is_admin)
       values (${user.userId}, ${user.userCode}, ${user.fullName},
       ${user.password}, false)""".update().apply()
    }
    user
  }

  def checkUser(userCode: String, password: String): Try[User] = Try {
    NamedDB('auth).readOnly { implicit session =>
      val maybeUser = sql"select * from users where user_code = $userCode".
        map(User.fromRS).single().apply()
      maybeUser match {
        case Some(user) =>
          if (BCrypt.checkpw(password, user.password)) user
          else throw new Exception("Password doesn't match")
        case None => throw new Exception("User is not found in the database")
      }
    }
  }
} 
开发者ID:getArtemUsername,项目名称:play-and-events,代码行数:52,代码来源:UserDao.scala


示例10: UserEntity

//设置package包名称以及导入依赖的类
package synahive.restapi.models

import org.mindrot.jbcrypt.BCrypt

case class UserEntity(id: Option[Long] = None, username: String, password: String) {
  require(!username.isEmpty, "username.empty")
  require(!password.isEmpty, "password.empty")

  def withHashedPassword(): UserEntity = this.copy(password = BCrypt.hashpw(password, BCrypt.gensalt()))
}

case class UserEntityUpdate(username: Option[String] = None, password: Option[String] = None) {
  def merge(user: UserEntity): UserEntity = {
    UserEntity(user.id, username.getOrElse(user.username), password.map(ps => BCrypt.hashpw(ps, BCrypt.gensalt())).getOrElse(user.password))
  }
} 
开发者ID:synahive,项目名称:synahive-server,代码行数:17,代码来源:UserEntity.scala


示例11: CheckUsersFile

//设置package包名称以及导入依赖的类
package util

import org.mindrot.jbcrypt.BCrypt

import scala.io.Source

object CheckUsersFile {

  val USERS_FILE = "/export/rkablog/users.txt"
  val FIELDS_SEPARATOR = ":"

  def checkLine(line: String): Boolean = {
    val lines = Source.fromFile(USERS_FILE).getLines()
    lines.contains(line)
  }

  def checkUsernamePassword(username: String, password: String): Boolean = {
    val lines = Source.fromFile(USERS_FILE).getLines()
    lines
      .map(_.split(FIELDS_SEPARATOR))
      .map(splitted => (splitted(0).trim(), splitted(1).trim))
      .filter(userPassword => userPassword._1 == username && BCrypt.checkpw(password, userPassword._2))
      .nonEmpty
  }

  def getUsernameLine(username: String): Option[String] = {
    val lines = Source.fromFile(USERS_FILE).getLines()
    lines.find(_.startsWith(username))
  }
} 
开发者ID:rkaraujo,项目名称:rkablog-scala,代码行数:31,代码来源:CheckUsersFile.scala


示例12: list

//设置package包名称以及导入依赖的类
package com.tennik.akkatcp.dao

import java.util.concurrent.{ ConcurrentHashMap, ConcurrentMap }

import com.tennik.akkatcp.models.User
import org.mindrot.jbcrypt.BCrypt

import scala.collection.JavaConverters._

trait UserDao {
  def list: Iterable[User]
  def find(userName: String): Option[User]
  def create(user: User): Option[User]
  def update(user: User): Option[User]
  def delete(userName: String): Option[User]
}

//in memory storage
class InMemoryUserDAO extends UserDao {

  val storage: ConcurrentMap[String, User] = new ConcurrentHashMap[String, User]()

  import InMemoryUserDAO._

  def init() {
    storage.put("admin", User("admin", pwd("password")))
    storage.put("user1", User("user", pwd("password1")))
    storage.put("user2", User("user", pwd("password2")))
  }

  init()

  def list: Iterable[User] = storage.values().asScala
  def find(userName: String): Option[User] = Option(storage.get(userName))

  def create(user: User): Option[User] = Option(storage.put(user.userName, User(user.userName, pwd(user.password))))
  def update(user: User): Option[User] = {
    val oldUser = storage.get(user.userName)
    storage.put(user.userName, User(user.userName, pwd(user.password)))
    Option(oldUser)
  }
  def delete(userName: String): Option[User] = {
    val oldUser = storage.get(userName)
    storage.remove(userName, oldUser)
    Option(oldUser)
  }
}

object InMemoryUserDAO {
  def pwd(p: String): String = BCrypt.hashpw(p, BCrypt.gensalt())
} 
开发者ID:antonveretennyk,项目名称:akkatcp,代码行数:52,代码来源:InMemoryUserDAO.scala


示例13: AuthenticationServiceImpl

//设置package包名称以及导入依赖的类
package services.security.Impl

import org.apache.commons.lang3.RandomStringUtils
import org.mindrot.jbcrypt.BCrypt
import services.security.AuthenticationService


class AuthenticationServiceImpl extends AuthenticationService{
  override def getHashedPassword(password: String): String = {
    BCrypt.hashpw(password, BCrypt.gensalt(12))
  }

  override def generateRandomPassword(): String = {
    val length: Int = 8
    val useLetters: Boolean = true
    val useNumbers: Boolean = true
    RandomStringUtils.random(length, useLetters, useNumbers)
  }

  override def checkPassword(candidate: String, hashed: String): Boolean = {
    BCrypt.checkpw(candidate, hashed)
  }
} 
开发者ID:boniface,项目名称:infoshareapi,代码行数:24,代码来源:AuthenticationServiceImpl.scala


示例14: Account

//设置package包名称以及导入依赖的类
package Models

import org.mindrot.jbcrypt.BCrypt
import scalikejdbc._

case class Account(id: Int, email: String, password: String, name: String, role: Role)

object Account extends SQLSyntaxSupport[Account]{

  private val a = syntax("a")

  def apply(a: SyntaxProvider[Account])(rs: WrappedResultSet): Account = autoConstruct(rs, a)

  private val auto = AutoSession

  def authenticate(email: String, password: String)(implicit s: DBSession = auto): Option[Account] = {
    findByEmail(email).filter { account => BCrypt.checkpw(password, account.password) }
  }

  def findByEmail(email: String)(implicit s: DBSession = auto): Option[Account] = withSQL {
    select.from(Account as a).where.eq(a.email, email)
  }.map(Account(a)).single.apply()

  def findById(id: Int)(implicit s: DBSession = auto): Option[Account] = withSQL {
    select.from(Account as a).where.eq(a.id, id)
  }.map(Account(a)).single.apply()

  def findAll()(implicit s: DBSession = auto): Seq[Account] = withSQL {
    select.from(Account as a)
  }.map(Account(a)).list.apply()

  private val ac = Account.column

  def addNewAccount(email: String, password: String, name: String, role: Role)(implicit s: DBSession = auto): Long = {
    val id = withSQL {
      val pass = BCrypt.hashpw(password, BCrypt.gensalt())
      QueryDSL.insert.into(Account).namedValues(
        ac.email -> email,
        ac.password -> pass,
        ac.name -> name,
        ac.role -> role.toString()
      )
    }.updateAndReturnGeneratedKey.apply()
    id
  }
} 
开发者ID:JamesMJordan,项目名称:GETTINREAL,代码行数:47,代码来源:Account.scala



注:本文中的org.mindrot.jbcrypt.BCrypt类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ParserRuleContext类代码示例发布时间:2022-05-23
下一篇:
Scala BodyParsers类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap