公司老項目使用
grails2.0+
版本,他的加密方式爲encodeAsSHA256
,數據是經過導入實現,要兼容之前數據加密方式,使之前使用老項目的用戶也能用原先的密碼登陸。java
def test() {
map.password1 = "123456".encodeAsSHA256()
map.password2 = springSecurityService.encodePassword("123456")
render map as JSON
}
複製代碼
src/main/goovy
下建立CustomPasswordEncoder.groovy
類,也能夠建立java
類package com.encoder
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder
import org.springframework.security.authentication.encoding.PasswordEncoderUtils
import org.springframework.security.crypto.codec.Hex
import org.springframework.util.Assert
import java.security.MessageDigest
/** * 自定義加密覆蓋默認加密方式 * 項目spring-security版本爲3.1.0,本能夠從新BaseDigestPasswordEncoder類 * 可是本人看BaseDigestPasswordEncoder類被標記爲刪除了,因此經過重寫MessageDigestPasswordEncoder類方法實現 */
class CustomPasswordEncoder extends MessageDigestPasswordEncoder {
// 默認爲MD5
private String algorithm = "MD5";
// 加密次數(提升安全)
private int iterations = 1;
CustomPasswordEncoder() {
// 當前類默認構造器,由於父類沒有空構造器,因此這裏必須調用父類有參構造,這裏傳入參數必須是父類存在的加密規則,不然報錯
super("SHA-256")
}
CustomPasswordEncoder(String algorithm) {
super(algorithm, false);
this.algorithm = algorithm
}
CustomPasswordEncoder(String algorithm, boolean encodeHashAsBase64) throws IllegalArgumentException {
super()
setEncodeHashAsBase64(encodeHashAsBase64);
this.algorithm = algorithm;
getMessageDigest();
}
@Override
String encodePassword(String rawPass, Object salt) {
String saltedPass = this.mergePasswordAndSalt(rawPass, salt, false)
MessageDigest messageDigest = this.getMessageDigest()
byte[] digest = messageDigest.digest(saltedPass.getBytes("UTF-8"))
for (int i = 1; i < iterations; i++) {
digest = messageDigest.digest(digest);
}
// 先判斷是否啓用base64
if (this.getEncodeHashAsBase64()) {
return new String(Base64.encodeAsBase64(digest))
// 判斷是否爲自定義的SHA-256-1(框架自定加密方式,非spring security框架,這裏指的是grails自帶的加密)
} else if ("SHA-256-1".equalsIgnoreCase(algorithm)) {
return rawPass.encodeAsSHA256()
} else {
// 使用用戶配置的其餘加密方式
return new String(Hex.encode(digest))
}
}
@Override
boolean isPasswordValid(String encPass, String rawPass, Object salt) {
String pass1 = "" + encPass
String pass2 = encodePassword(rawPass, salt)
return PasswordEncoderUtils.equals(pass1, pass2)
}
String getAlgorithm() {
return algorithm;
}
void setIterations(int iterations) {
Assert.isTrue(iterations > 0, "Iterations value must be greater than zero");
this.iterations = iterations;
}
}
複製代碼
grails-app/conf/spring/resources.groovy
中註冊一下bean
beans = {
// 自定義密碼
passwordEncoder(com.encoder.CustomPasswordEncoder) {
encodeHashAsBase64 = false // 若爲true,則以base64方式加密
}
}
複製代碼
grails-app/conf/application.groovy
中添加配置// 原框架加密方式,有SHA-25六、bcrypt、MD五、pbkdf2,默認爲bcrypt
// 自定義加密默認爲MD5,這裏SHA-256-1爲自定義加密,還能夠用SHA-256等
grails.plugin.springsecurity.password.algoritham = 'SHA-256-1'
複製代碼
domain.save(failOnError: true)
的有時須要修改成domain.save(flush: true)
,我測試密碼修改時,failOnError: true
沒有修改爲功。參考spring