I'm inserting users into a H2 database as follows:
insert into users (id,username,password) VALUES(1,'user','password');
I'm also using spring security. Usually to hash passwords I'd configure Spring like this:
<bean id = "encoder" class = "org.springframework.security.crypto.password.StandardPasswordEncoder"/>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="encoder" />-->
</security:authentication-provider>
</security:authentication-man
and put a hash function into the insert statement. The H2 documentation suggests I need to do this:
insert into users (id,username,password) VALUES(1 vg,'user',HASH('SHA256', STRINGTOUTF8('Password'), 1000));
but when I do, the passwords don't seem to match. I expect I'm not configuring something properly, but google isn't helping me.
Do the convesion in java, using spring
final StandardPasswordEncoder encoder = new StandardPasswordEncoder();
String hashedPassword = encoder.encode(aStringVarOfThePassword);
Related
I'm trying to set up a TURN server for a project using Coturn but am finding that documentation is sketchy at best...
I realise that there is a turnadmin tool that will do this for you, but I would greatly prefer to just run queries on my database directly. This is an app with potentially many users and their shared keys (hmackey in turnusers_lt) are subject to change (in order to not share passwords with the app the app uses a 'fake' password which is a hash of certain volatile user parameters that aren't so secret).
I can gather from the scant docs that the hmackey is computed using the realm, username and password:
$ turnadmin -k -u myusername -r my.realm.org -p my-password
> e.g. 0x7a69b0e2b747a4560045f79d171b78c0
Given that my code will know these three parameters, how do I build the hmac hash? E.g. in PHP I have
string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )
$algo here should be SHA1, but what values would go into $data (e.g. concat of user/pass) and $key (e.g. realm)?
There's also a turn_secret table listing a 'value' for a realm, I was guessing this should be used as the $key in the above example, but adding and modifying the keys still give the same result when I call turnadmin.
Essentially, what I want to do is (pseudo-code):
// user registers
// pseudo-code, this is of course computed using php's password_hash function
$hashed_pw = hash($pw);
$db->query('insert into usertable (name, pass) values ($name, $hashed_pw)');
// this is implemented somewhere...
$coturn_pw = get_secret_hash($name);
// this needs implementing...
$HAMC = calc_hmac($name, $coturn_pw, 'my.realm.com');
$turndb->query('insert into turnusers_lt values (...)');
// on update, delete also update turnusers_lt
...and then in the client, I should now be able to connect to the TURN server using $name and $coturn_pw as credentials for my.realm.com.
Or am I over-thinking this and should I just use a generic user for my app, hardcode the password and let Coturn figure out who is talking to who?
How to build the HMAC key is described in RFC 5389:
key = MD5(username ":" realm ":" SASLprep(password))
where MD5 is defined in RFC 1321 and SASLprep() is defined in RFC 4013
The only table you need to update is turnusers_lt. The turn_secret table and SHA1 algorithm is used for generating time-limited credentials.
INSERT INTO turnusers_lt (realm, name, hmackey) VALUES (:realm, :username, :key);
And of course, use prepared statements rather than building the SQL string manually.
OrangeDog answer is correct.
With node.js:
const crypto= require("crypto");
const username= "foo";
const realm= "here";
const password= "secret";
const hmac = crypto
.createHash("md5")
.update(`${username}:${realm}:${password}`)
.digest("hex")
;
I have a simple spring project which try to retrieve a document from couchbase using spring-data-couchbase. I have configured the config by extending AbstractCouchbaseConfiguration. Everything works perfectly fine.
Since I use couchbase as a cache, now I need to set the operation timeout to a lower value. Anybody can shed some light on how to do it?
According to the docs, the correct answer is wrong. That's not the way it should be done...
When you extend from AbstractCouchbaseConfiguration
Default settings can be customized through the DefaultCouchbaseEnvironment.Builder or through the setting of system properties. Latter ones take always precedence and can be used to override builder settings at runtime too. http://docs.couchbase.com/sdk-api/couchbase-java-client-2.0.0/com/couchbase/client/java/env/DefaultCouchbaseEnvironment.html
For instance, to customize the timeout connection:
#Override
protected CouchbaseEnvironment getEnvironment() {
DefaultCouchbaseEnvironment.builder().connectTimeout(15000);
return super.getEnvironment();
}
There are other options that can be assigned this way.
According the docs (https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html ),
Here is the application.properties :
spring.couchbase.env.timeouts.connect=5000ms # Bucket connections timeouts.
spring.couchbase.env.timeouts.key-value=2500ms # Blocking operations performed on a specific key timeout.
spring.couchbase.env.timeouts.query=7500ms # N1QL query operations timeout.
spring.couchbase.env.timeouts.socket-connect=1000ms # Socket connect connections timeout.
spring.couchbase.env.timeouts.view=7500ms # Regular and geospatial view operations timeout.
To define a timeout for the CouchbaseClient you have to provide it using the ConnectionFactory. Sadly, the current version of spring-data-couchbase doesn't provide a simple way to do that.
The class responsible to create connection factories is ConnectionFactoryBean, and it has a setter for the operations timeout, but I couldn't find anything for #Configuration classes.
Since you are extending AbstractCouchbaseConfiguration, you might want to override couchbaseClient():
public class MyCouchbaseConfiguration extends AbstractCouchbaseConfiguration {
...
private final CouchbaseConnectionFactoryBuilder builder = new CouchbaseConnectionFactoryBuilder();
private CouchbaseConnectionFactory connectionFactory;
...
#Override
#Bean(destroyMethod = "shutdown")
public CouchbaseClient couchbaseClient() throws Exception {
setLoggerProperty(couchbaseLogger());
if(connectionFactory == null){
builder.setOpTimeout(myTimeout);
// Set another parameters.
...
connectionFactory = builder.buildCouchbaseConnection(
bootstrapUris(bootstrapHosts()),
getBucketName(),
getBucketPassword()
);
}
return new CouchbaseClient(connectionFactory);
}
}
Also, you can call directly CouchbaseFactoryBean but it's not a good practice if you are not configuring your application using XML bean definitions.
Here is the XML configuration just in case:
<bean id="couchbase" class="org.springframework.data.couchbase.core.CouchbaseFactoryBean">
<property name="opTimeout" value="1000"/> <!-- 1 sec -->
<property name="bucket" value="myBucket"/>
<property name="password" value="myPassword"/>
<property name="host" value="myHost"/>
</bean>
<couchbase:template id="couchbaseTemplate"/>
For Spring Data Couchbase 2, adding the following property in application.properties did it
spring.couchbase.env.timeouts.connect=20000
I used queryTimeout to set the value of operation timeout as shown below:
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
.connectTimeout(50000).socketConnectTimeout(50000)
.queryTimeout(1000)
.build();
this will ensure you get the response within 1s.
use this link to get different available options:
https://docs.couchbase.com/java-sdk/2.7/client-settings.html#timeout-options
I'm trying to invoke ProfileFormHandler's create handle using ATG rest client as shown below.
mSession = RestSession.createSession(mHost, mPort,"kim#example.com","password");
mSession.setUseHttpsForLogin(false);
mSession.login();
Map<String,Object> params = new HashMap<String,Object>();
params.put("value.login", "buddha#oracle.com");
params.put("value.email", "buddha#oracle.com");
params.put("value.password", "password");
RestResult result = RestComponentHelper.executeMethod("/atg/userprofiling/ProfileFormHandler","create",null,params,mSession);
I'm getting form exceptions that says, I'm not passing Login and Password Fields.
["Missing value for the required property Password",
"Missing value for the required property Login name"]
I've tried all combinations of login and password fields like value.login, Login, login, value.Login etc., but nothing seemed to work. All combinations giving the same form exceptions.
How do I invoke an ATG form handler using ATG REST Client and pass parameters to it?
Definitely need more information but looking at your code I can see that you have a value.login which is not configured ootb and believe this is causing the NPE. Assuming you have not customized the ootb ATG RegistrationFormHandler and the required field in the repository the only values you need to pass to the form handler are:
value.email
value.password
value.confirmPassword
value.firstName
value.lastName
Also, the help is specific that the data-type of the value property needs to be java.util.Dictionary
Add the following to /atg/rest/security/restSecurityConfiguration.xml
<resource component="/atg/userprofiling/ProfileFormHandler" secure="false">
<method name="handleCreate" secure="false">
<acl value="EVERYONE:read,write,execute" />
</method>
<property name="value.login" secure="false" />
<property name="value.password" secure="false" />
</resource>
I had to migrate a legacy database with clear text password to a PostgresSQL database. I've looked up what's the best way to encrypt password in a database and found the pgcrypto extension with slow algorithm. (see pgcrypto documentation for 8.4)
The migration is done for data and everything is working well.
Now I have to write a CRUD application to handle this data.
I'm wondering what's the best way to use this strong encryption with grails ?
In my model, I've used the afterInsert event to handle this :
def afterInsert() {
Compte.executeUpdate("update Compte set hashpass=crypt(hashpass, gen_salt('bf', 8)) where id = (:compteId)", [compteId: this.id])
}
I guess that I should also check if the hashpass field is modified whenever the model is saved. But before that, is there another (best) way to achieve my goal ?
Edit : I cannot use the Spring Security bcrypt plugin here. The CRUD application that I'm writing use SSO CAS so I don't need such a plugin. The CRUD application manages accounts for another application that I don't own. I just need to create a new account, modify or delete an existing one. This is very simple. The tricky part is to hack grails so that it takes into account the password field and use a specific sql to store it to a postgreSQL database.
Edit 2 :
I've come up with the following code but it doesn't work
def beforeInsert() {
hashpass = encodePassword(hashpass);
}
def encodePassword(cleartextpwd) {
// create a key generator based upon the Blowfish cipher
KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
// create a key
SecretKey secretkey = keygenerator.generateKey();
// create a cipher based upon Blowfish
Cipher cipher = Cipher.getInstance(ALGORITHM);
// initialise cipher to with secret key
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
// get the text to encrypt
String inputText = cleartextpwd;
// encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes("UTF-8"));
return Base64.encodeBase64String(encrypted);
}
I get a hash that is not a blowfish hash (beginning with $2a$08$ )
Edit 3 :
I've finally came up with a cleaner grails solution after reading this wiki page : grails.org/Simple+Dynamic+Password+Codec (not enough reputation to put more than 2 links so add http:// before) and the bug report jira.grails.org/browse/GRAILS-3620
Following advice from #lukelazarovic, I've also used the algorithm from the spring security plugin.
Here is my password encoder to put into grails/utils :
import grails.plugin.springsecurity.authentication.encoding.BCryptPasswordEncoder;
class BlowfishCodec {
static encode(target) {
// TODO need to put the logcount = 8 in configuration file
return new BCryptPasswordEncoder(8).encodePassword(
target, null)
}
}
I've updated my Compte model to call my password encoder before saving / updating the data :
def beforeInsert() {
hashpass = hashpass.encodeAsBlowfish();
}
def beforeUpdate() {
if(isDirty('hashpass')) {
hashpass = hashpass.encodeAsBlowfish();
}
}
The tricky part is to hack grails so that it takes into account the
password field and use a specific sql to store it to a postgreSQL
database.
Is there any particular reason to do the hashing in database?
IMHO it's better to hash the password in Grails, therefore have a code that is not database-specific and easier to read.
For hashing passwords using Blowfish algorithm using Java or Groovy see Encryption with BlowFish in Java
The resulting hash begins with algorithm specification, iteration count and salt, separated with dollar sign - '$'. So the hash may look like "$2a$08$saltCharacters" where 2a is a algorithm, 08 is iteration count, then follows salt and after salt is the hash itself.
For broader explanation see http://www.techrepublic.com/blog/australian-technology/securing-passwords-with-blowfish. Don't mind that it concerns to Blowfish in PHP, the principles applies for Java or Groovy as well.
So, I new with Spring Security. I'm using password hashing with salt.In security xml file, it looks like:
<beans:bean id="saltSource" class="bla.bla.MyOwnSalt" scope="singleton" />
<password-encoder hash="md5" >
<salt-source ref="saltSource" />
MyOwnSalt implements SaltSource.
So passwords hash creating with salt.
Sometimes I need to create users and their passwords directly in database.
The main question is: How can I create a hash using only MD5 calculator, if I have password and salt?
I was trying to create hash from "passwordsalt". Spring password-encoder with salt-source works like: PasswordEncoder.encode("password{salt}");
So, the problem was with missed{ }
All I had to - is to look at the PasswordEncoder source code.