2013-08-10 3 views
0

Я хочу создать модуль под названием User. Этот модуль состоит из имени, имени пользователя, телефонаNo и пароля. Я хочу зашифровать и уменьшить пароль с помощью алгоритма RSA.Зашифровать пароль Grails с помощью rsa

это мой RSA.Java

import java.math.BigInteger; 
import java.security.SecureRandom; 

/** 
* Simple RSA public key encryption algorithm implementation. 
*/ 

public class RSA { 
    private BigInteger n, d, e; 

    private int bitlen = 1024; 

    /** Create an instance that can encrypt using someone elses public key. */ 
    public RSA(BigInteger newn, BigInteger newe) { 
    n = newn; 
    e = newe; 
    } 

    /** Create an instance that can both encrypt and decrypt. */ 
    public RSA(int bits) { 
    bitlen = bits; 
    SecureRandom r = new SecureRandom(); 
    BigInteger p = new BigInteger(bitlen/2, 100, r); 
    BigInteger q = new BigInteger(bitlen/2, 100, r); 

    n = p.multiply(q); 
    BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); 

    e = new BigInteger("3"); 
    while (m.gcd(e).intValue() > 1) { 
     e = e.add(new BigInteger("2")); 
    } 
    d = e.modInverse(m); 
    } 

    /** Encrypt the given plaintext message. */ 
    public synchronized String encrypt(String message) { 
    return (new BigInteger(message.getBytes())).modPow(e, n).toString(); 
    } 

    /** Encrypt the given plaintext message. */ 
    public synchronized BigInteger encrypt(BigInteger message) { 
    return message.modPow(e, n); 
    } 

    /** Decrypt the given ciphertext message. */ 
    public synchronized String decrypt(String message) { 
    return new String((new BigInteger(message)).modPow(d, n).toByteArray()); 
    } 

    /** Decrypt the given ciphertext message. */ 
    public synchronized BigInteger decrypt(BigInteger message) { 
    return message.modPow(d, n); 
    } 

    /** Generate a new public and private key set. */ 
    public synchronized void generateKeys() { 
    SecureRandom r = new SecureRandom(); 
    BigInteger p = new BigInteger(bitlen/2, 100, r); 
    BigInteger q = new BigInteger(bitlen/2, 100, r); 
    n = p.multiply(q); 
    BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q 
     .subtract(BigInteger.ONE)); 
    e = new BigInteger("3"); 
    while (m.gcd(e).intValue() > 1) { 
     e = e.add(new BigInteger("2")); 
    } 
    d = e.modInverse(m); 
    } 

    /** Return the modulus. */ 
    public synchronized BigInteger getN() { 
    return n; 
    } 

    /** Return the public key. */ 
    public synchronized BigInteger getE() { 
    return e; 
    } 
} 

Это мой домен User.groovy:

class User{ 

    String name 
    String username 
    String phoneNo 
    String password 

} 

Это мой UserController.groovy: (сохранение и обновление)

class UserController { 

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"] 

    def index = { 
     redirect(action: "list", params: params) 
    } 

    def save = { 
     def userInstance = new User(params) 
     if (userInstance .save(flush: true)) { 
      flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance .id])}" 
      redirect(action: "show", id: userInstance .id) 
     } 
     else { 
      render(view: "create", model: [userInstance : userInstance ]) 
     } 
    } 


    def edit = { 
     def userInstance = User.get(params.id) 
     if (!userInstance) { 
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}" 
      redirect(action: "list") 
     } 
     else { 
      return [userInstance : userInstance ] 
     } 
    } 

    def update = { 
     def userInstance = User.get(params.id) 
     if (userInstance) { 
      if (params.version) { 
       def version = params.version.toLong() 
       if (userInstance .version > version) { 

        userInstance .errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Another user has updated this User while you were editing") 
        render(view: "edit", model: [userInstance : userInstance ]) 
        return 
       } 
      } 
      userInstance .properties = params 
      if (!userInstance .hasErrors() && userInstance .save(flush: true)) { 
       flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance .id])}" 
       redirect(action: "show", id: userInstance .id) 
      } 
      else { 
       render(view: "edit", model: [userInstance : userInstance ]) 
      } 
     } 
     else { 
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}" 
      redirect(action: "list") 
     } 
    } 
} 

Что я должен добавить в свой контроллер сохранения и редактирования, поэтому, когда я сохраняю форму, зашифрованную пароль, тогда, когда я отредактирую форму пароль будет расшифрован? Пожалуйста, помогите мне, потому что я новичок в Java и Граалей, спасибо большое :)

ответ

1

SpringSecurity Plugin Аналогично, вы можете использовать beforeInsert и beforeUpdate событие, чтобы сделать преобразование на свой пароль. В этом методе реализовано ваше шифрование.

class User { 

    transient springSecurityService 

    String username 
    String password 
    boolean enabled 
    boolean accountExpired 
    boolean accountLocked 
    boolean passwordExpired 

    static constraints = { 
     username blank: false, unique: true 
     password blank: false 
    } 

    static mapping = { 
     password column: '`password`' 
    } 

    Set<Role> getAuthorities() { 
     UserRole.findAllByUser(this).collect { it.role } as Set 
    } 

    def beforeInsert() { 
     encodePassword() 
    } 

    def beforeUpdate() { 
     if (isDirty('password')) { 
      encodePassword() 
     } 
    } 

    protected void encodePassword() { 
     password = springSecurityService.encodePassword(password) 
    } 
} 
+0

Срок действия истек истечения срока действия? согласно сценарию есть Роль, это означает, что я должен добавить новый домен роли пользователя? не так ли? – dope

+0

Это пример основного пользовательского объекта Spring Security, если вы загружаете свою собственную безопасность, вам может и не понадобиться. Я разместил это здесь, чтобы вы могли видеть, как используются beforeInsert и beforeUpdate. Как вы можете видеть, они кодируютPassword перед вставкой и когда обновляются записи. – Alidad

Смежные вопросы