I tried to encrypt a password in Griffon, but I don't know how to do that. Usually I'd use md5 in another language, but what in griffon?
Here is a bit of my code:
if (sql.firstRow("SELECT userID FROM tbluser WHERE userID = ${model.userID}") != null) {
// usually in SQL like this
user.executeUpdate("UPDATE tbluser SET username = ${model.username}, password = md5(${model.password}), level = ${model.level} WHERE userID = ${model.userID}")
edt {
int index = model.listUser.findIndexOf{it['userID'] == model.userID}
model.listUser[index] += [username: model.username, password: model.password, level: model.level] --> how to do md5 here?
}
} else {
user.add(userID: model.userID, username: model.username, password: model.password, level: model.level) --> and here?
edt { model.listUser << [userID: model.userID, username: model.username, password: model.password, level: model.level] }
}
I just get a sample code about it and it worked.
Here the code:
import java.security.MessageDigest
String generateMD5(String s) {
MessageDigest digest = MessageDigest.getInstance("MD5")
digest.update(s.bytes);
return new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')
}
for my case: generateMD5(model.password)
Per se encryption is not related to Griffon, as it's just a transformation of a character/byte array. However there's a bcrypt plugin available that applies the BCrypt algorithm http://artifacts.griffon-framework.org/plugin/bcrypt
More information on BCrypt can be found at http://codahale.com/how-to-safely-store-a-password/
I'm very new to griffon but i think this can help you.
I hope i could help you with this.
Codesearch Griffon MD5
Related
Prompt me, please, how can I get separately a value for key paswd-0. I mean, I need separated values for password and username.
This is remote data from data.terraform_remote_state.user_passwd.outputs.login_passwd
output = {
paswd-0 = jsonencode(
{
password = "uGo="
username = "git"
}
)
paswd-1 = jsonencode(
{
password = "wM="
username = "kun"
}
)
}
I'm trying this and get error parameter: lookup() requires a map as the
output "tetts" {
value = lookup(tomap(data.terraform_remote_state.user_passwd.outputs.login_passwd.paswd-0), "password", null)
}
Ideally I would go through of each value and fill these fields.
argocd_repositories = {
[
"private-repo" = {
url = "https://repo.git"
username = "argocd"
password = "access_token"
},
"git-repo" = {
url = "https://repo.git"
password = "argocd_access_token"
username = "admin"
},
"private-helm-chart" = {
url = "https://charts.jetstack.io"
type = "helm"
username = "foo"
password = "bar"
},
]
}
As per my comment, you can get the value from the data source by using the jsondecode built-in function [1]. You would have to update the output to look like the following:
output "tetts" {
value = lookup(tomap(jsondecode(data.terraform_remote_state.user_passwd.outputs.login_passwd["paswd-0"]), "password", null)
}
This is only to make it work as you intended it to. However, it will output only the value for the password. Since I do not have the remote state, I managed to get close to what you want with locals and the following:
locals {
output = {
paswd-0 = jsonencode(
{
password = "uGo="
username = "git"
}
)
paswd-1 = jsonencode(
{
password = "wM="
username = "kun"
}
)
}
sorted_values = { for k, v in local.output : jsondecode(v).username => jsondecode(v).password }
}
Note that jsondecode is used on the values of the original map. Furthermore, since the JSON decoded values are also in a key value pair format, you can access the keys and corresponding values using the usual terraform notation (i.e., jsondecode(v).username and jsondecode(v).password). Using terraform console, the local sorted_values variable has the following look:
> local.sorted_values
{
"git" = "uGo="
"kun" = "wM="
}
I guess this is close to what you wanted to achieve with the tomap function.
[1] https://www.terraform.io/language/functions/jsondecode
I am trying to create a JWE Token using the node-jose library's createEncrypt method. The problem is, I want to set the kid to a certain value. But when importing the key using the jose.JWK.asKey method, it's automatically calculating the kid and won't let me change/set it. Here is the sample code:
const { JWK, JWE } = require('node-jose');
encrypt = async (raw, format = 'compact', contentAlg = "A128CBC-HS256", alg = "RSA-OAEP-256") => {
let _publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxO+O52a1eAkbYatqpPAk
vhTz5VAdNloWhbmAmwPQl9202VKxU+yOCbwZSU8NqwVubHMgnxdycgJw+zGslXgz
zHPpmA5evOY2AVjpcE9avKfp523M5gxOaAnQCxat6KxORIJWLSF84EUtrzLIxgle
bvDyhfoHMGVSYiP89UQPTR+uu6irFRkdu2zFDPOx2/4XdtyAbJlWdj4Fes0v3CcA
/jDO9EmwVEiySCuagLWnrvHvCV0mCDN167JSVjeeKZy4Q36WyF0VqytxmW+mXn+m
IfcLlj5vXSXp81pI1Iyg86KZtW3A6dP8QuRlYwHJU7Z+m7AeIHtC+ol0/eBPYPwk
PQIDAQAB
-----END PUBLIC KEY-----`
let publicKey = await JWK.asKey(_publicKey, "pem");
publicKey.kid = "932ea6bb-2623-4dc3-96b1-c4be61e97569";
console.log(publicKey)
const buffer = Buffer.from(JSON.stringify(raw))
const encrypted = await JWE.createEncrypt({ format: format, contentAlg: contentAlg, fields: { alg: alg, iat: (new Date().getTime()), exp: 30000} }, publicKey)
.update(buffer).final();
return encrypted;
}
let raw = {
"mobileNumber": "1234567890",
"customerId": "000000000",
"sessionId": "3a600342-a7a3-4c66-bbd3-f67de5d7096f",
};
encrypt(raw).then((data)=> {console.log(data)})
Here is the encrypted JWE Token generated:
eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJpYXQiOjE2NDAyNDU0NzY5ODEsImV4cCI6MzAwMDAsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJraWQiOiI1bUxtdmVHdng0RHVucGlfTnBhajhxZlByRHNDYW9NV29JeWRoM003SzA4In0.SUpO7X0XXbkqQtNGVvLMNo6oGi1GrTzAR1FtXlL8ngg9Uvd91nkLiRqgcmjKBBEE1M330WV_HrUYNs2NVRcXTDcr41fSwvHSu7veK_YDj-m73LoMKlmojeB6GIRUIXIw7oaqgFSOSb_Xgq_zwG9WGa07h2OgOzeFxKNJCvt1J2i_v2Tt61yyet0hdMinT78whDGgf_JW4LUSaXY9wsqsuQSDkKWFLvxHqNmq7nGPLpgEJjm1GPF0slPvdWsARsMEttbPK9VpoMUvMcqy5bWVWSmj2MEGTVw6ua-uFw9fEgyn095wl-s8lEfZFkFaiFN7ps5VwqVV2tihpnYrCVIYAA.jxR4Gw_Gcy9Sexw-wMBKtQ.TzugQZCFgQiolIBc2FAEQ0ZbvNdPFzE2z0m9cFxWQtADEijOCzQjZreVvnsVjHFXdP_w-YcnCbmKXkwalWnFMo7wkjuuJ0fAsTfTOEiBjuIPvMa0k04C97Rc4ZYszzzL7xxwW0RnqoNxiQMkea3H0A.qAqgcg_DLV1vHzb0EIq-9A
If you check this on jwt.io, you can see the kid is already calculated & set. How can I set/change the kid here?
The kid is calculated automatically, when it's not known during the import:
When importing or generating a key that does not have a "kid" defined, a "SHA-256" thumbprint is calculated and used as the "kid".
(see https://github.com/cisco/node-jose#obtaining-a-keys-thumbprint)
But in the call to JWK.asKey, you can pass an additional parameter extras, that sets values for existing fields or contains additional fields for the JWK.
For your use case, you can set a kid as a JSON object
let kid = "932ea6bb-2623-4dc3-96b1-c4be61e97569";
let publicKey = await JWK.asKey(_publicKey, "pem", {"kid":kid});
console.log(publicKey.toJSON())
Output:
{
kty: 'RSA',
kid: '932ea6bb-2623-4dc3-96b1-c4be61e97569',
n: 'xO-O52a1eAkbYatqpPAkvhTz5VAdNloWhbmAmwPQl9202VKxU-yOCbwZSU8NqwVubHMgnxdycgJw-zGslXgzzHPpmA5evOY2AVjpcE9avKfp523M5gxOaAnQCxat6KxORIJWLSF84EUtrzLIxglebvDyhfoHMGVSYiP89UQPTR-uu6irFRkdu2zFDPOx2_4XdtyAbJlWdj4Fes0v3CcA_jDO9EmwVEiySCuagLWnrvHvCV0mCDN167JSVjeeKZy4Q36WyF0VqytxmW-mXn-mIfcLlj5vXSXp81pI1Iyg86KZtW3A6dP8QuRlYwHJU7Z-m7AeIHtC-ol0_eBPYPwkPQ',
e: 'AQAB'
}
Using Xcode 7 beta, Swift 2.0
I'm saving and loading credentials to keychain, somehow when loading I get "Optional(value)" back, it looks like this is really part of the string as it also displayed like so in a textbox or when sending to API
This is how I save and load credentials now, as you see I've done a lot of extra nil checking to make sure it is not nil or Optional, it is indeed a overuse of explanation marks...
func SaveCredentials(credentials : [String : String!]!) -> Bool
{
if(credentials.count == 2)
{
//only proceed when we have two keys: username and password
let username = credentials["username"]
let password = credentials["password"]
if let usernameStr = username
{//also tried username!=nil && password != nil
if let passwordStr = password
{ //usernameStr and passwordStr is of type String!
let NsDataUsername = usernameStr!.dataUsingEncoding(NSUTF8StringEncoding)
let NsDataPassword = passwordStr!.dataUsingEncoding(NSUTF8StringEncoding)
if(NsDataUsername != nil && NsDataPassword != nil)
{
LocalStorage.saveToKeyChain("username", data: NsDataUsername!)
LocalStorage.saveToKeyChain("password", data: NsDataPassword!)
return true
}
}
}
}
return false
}
func LoadCredentials() -> [String : String!]?
{
let NsDataUsername = LocalStorage.loadFromKeyChain("username")
let NsDataPassword = LocalStorage.loadFromKeyChain("password")
if(NsDataUsername != nil && NsDataPassword != nil)
{
let username : String! = String(NSString(data: NsDataUsername!, encoding: NSUTF8StringEncoding))
let password : String! = String(NSString(data: NsDataPassword!, encoding: NSUTF8StringEncoding))
if let usernameStr = username
{
if let passwordStr = password
{ // password is of type String!, passwordStr is of type String
var credentials : [String: String!] = [String : String]()
credentials["username"] = usernameStr
credentials["password"] = passwordStr
return credentials
}
}
}
return nil
}
And when I send to Api, this is my method that also requires a non-optional string. This method does work when logging in, getting strings from text fields, but does not filter out that Optional when coming from keychain.
func LoginUser(email : String!, password : String!)
{
print("LoginUser(email : \(email), password: \(password))")
var parameters = [String : AnyObject]()
parameters["UserName"] = email
parameters["Password"] = password
......
The strings that I send to the SaveCredentials method, are the same that the user logged in with:
func LoginLocalAccount(email : String!, password : String!)
{
databaseAPI.LoginUser(email!, password: password!) //login goes just fine
saveCredentials(email!, password: password!) //manages to get Optional in it..
}
I suspect it has something to do with saving and loading from keychain, for interests, this is what I use to save and load from keychain.
I want to get rid of them because when the app starts, it loads the credentials and tries to login at my API. Ofcourse I get an error back that the username is not a valid e-mail, because it is Optional(email#adress.com)
You're overusing !. You don't need them. Try to learn more about implicitly unwrapped optionals, optionals, ... Your code is a mess (no offense, everybody's learning).
Back to your optional problem, it's caused by this line:
let username : String! = String(NSString(data: NsDataUsername!, encoding: NSUTF8StringEncoding))
convenience init?(data: NSData, encoding: UInt) - inner part utilizes failable initializer, so, NSString? is the result. Then initialization of String with optional NSString? produces optional as well. But, it has no sense at all do it in this way.
First part - remove optional
Utilizing new guard:
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
loadedPassword contains NSString (not NSString?) now.
Second part - NSString -> String
You did probably read (if not, read) Strings and Characters about bridging, ... If you can freely exchange NSString with String, you can think that you're done:
var dict = [String:String]()
dict["password"] = loadedPassword
Nope. It produces following error:
NSString is not implicitly convertible to String; did you mean to
use 'as' to explicitly convert?
Slight change and now you're done:
var dict = [String:String]()
dict["password"] = loadedPassword as String
Complete example
let password = "Hallo"
guard let passwordData = password.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("Ooops")
}
// save/load to/from keychain
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
var dict = [String:String]()
dict["password"] = loadedPassword as String
print(dict) // "[password: Hallo]\n"
I'm new to kohana 3.2 and i couldnt find any answer regrading the auth module.
this is my code and forsome reason ever since i changed the user model to extend model_auth_user
the validation isnt being done prooperly. The password field can be inserted empty and no excpetion will be caught and same if the password_confirm and password fields are different:
public function action_new()
{
if ($_POST){
try
{
$user = ORM::factory('user')
->values(array(
'username' => $_POST['username'],
'email' => $_POST['email'],
'password' => $_POST['password'],
'password_confirm' => $_POST['password_confirm']));
$user->save();
$user->add('roles', ORM::factory('role', array('name' => 'login')));
$this->request->redirect('user/index');
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors();
}
}
$view = View::factory('user/new')
->bind('errors',$errors); //pass the info to the view
$this->response->body($view); //show the view
}
thanks
You can override run_filter() method to force Kohana ignore password filtering in case of empty value. For example, put this code to your User_Model:
protected function run_filter($field, $value)
{
if ($field === "password" AND $value === "")
return "";
parent::run_filter($field, $value);
}
Try code sample from Model_Auth_User::create_user();
$user->save(Model_User::get_password_validation($_POST)->rule('password', 'not_empty'));
This validation execute before filters(hashing password). After hashing - blank password becomes not empty string.
security.yml:
providers:
main:
entity: { class: Tg\UserBundle\Entity\User, property: username }
encoders:
Tg\UserBundle\Entity\User: sha512
In my manager during registration I set the password:
$encoder = $this->encoder->getEncoder($user);
$raw = $user->getPassword();
$salt = $user->getSalt();
$encoded = $encoder->encodePassword($raw, $salt);
if (!$encoder->isPasswordValid($encoded, $raw, $salt)) {
throw new \Exception('Password incorrectly encoded during user registration', 428);
} else {
$user->setPassword($encoded);
}
In my User entity I have the basic salt on construct:
$this->salt = md5(uniqid(null, true));
I receive error on default login template:
The presented password is invalid.
Wtf?
This is not exactly an answer (i can't figure out why you r example is not working). But I'm using sha512 base64 encoded and this setup is working fine for me:
security:
encoders:
Acme\HelloBundle\Entity\User:
algorithm: sha512
encode_as_base64: true
iterations: 10
Salt initialization in User class:
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
Hope this helps.
I just hit this error as well. You need to make sure you password field can support the sha512 hash size. I think the tutorials make the password field default to a size of 40. You need to extend this to a larger size (125).