Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Код в JAVA (хеширование(нужно снять)) 
:(
    Опции темы
Sobstvennaya
Дата 5.1.2009, 21:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 20
Регистрация: 31.12.2008

Репутация: нет
Всего: нет



Здравствуйте. Снимите пожалуйсто правльно 
Хеширование SHA1. А то я боюсь что нибудь испортить код выдаст ошибку (base 64 оставляемс) 

Код

// o initialization 
// --------------- 
Accounts acc = null; 

// o Encode Password 
// ---------------- 
MessageDigest md; 
byte[] newpass; 
try 
{ 
md = MessageDigest.getInstance("SHA"); 
newpass = password.getBytes("UTF-8"); 
newpass = md.digest(newpass); 
} 
catch (NoSuchAlgorithmException e1) 
{ 
throw new AccountModificationException("No algorithm to encode password.", e1); 
} 
catch (UnsupportedEncodingException e1) 
{ 
throw new AccountModificationException("Unsupported encoding.", e1); 
} 

// o update account 
// ---------------


Это сообщение отредактировал(а) powerOn - 5.1.2009, 21:51
PM MAIL ICQ Skype   Вверх
rygel
Дата 5.1.2009, 22:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 110
Регистрация: 21.9.2007
Где: Харьков

Репутация: 6
Всего: 7



Если я правильно понял, то просто уберите весь этот код и используйте переменную password - это и есть ваш пароль без хеширования.
(Другое дело если в базе уже хранятся хеши, и убрав хеширование пользователь не пройдет процедуру логина)

Base64 здесь нет, лишь получается хеш.



Это сообщение отредактировал(а) rygel - 5.1.2009, 23:18
PM MAIL   Вверх
Sobstvennaya
Дата 5.1.2009, 23:08 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 20
Регистрация: 31.12.2008

Репутация: нет
Всего: нет



в том и дело что base64 нужно оставить...на остальное все код ложил. и дело в том что я не умею переписывать ничего) как я это все уберу то : ( ... 
PM MAIL ICQ Skype   Вверх
rygel
Дата 5.1.2009, 23:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 110
Регистрация: 21.9.2007
Где: Харьков

Репутация: 6
Всего: 7



в том коде который вы привели есть лишь применение хеш-функции к паролю. никакого base64 здесь нет... или вам нужно заменить sha на base64?
PM MAIL   Вверх
Sobstvennaya
Дата 6.1.2009, 13:42 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 20
Регистрация: 31.12.2008

Репутация: нет
Всего: нет



Нет..заменять ничего не нужно. Только снять хеширование. Вот полный код (: ...

Код

$HeadURL: $
 *
 * $Author: $
 * $Date: $
 * $Revision: $
 *
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package com.l2jfree.loginserver.services;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.l2jfree.tools.codec.Base64;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ObjectRetrievalFailureException;

import com.l2jfree.loginserver.beans.Accounts;
import com.l2jfree.loginserver.dao.AccountsDAO;
import com.l2jfree.loginserver.services.exception.AccountModificationException;

/**
 * Account service to handle account management
 * 
 */
public class AccountsServices
{
    private static Log    _log        = LogFactory.getLog(AccountsServices.class);

    private AccountsDAO    __accDAO    = null;

    public void setAccountsDAO(AccountsDAO accDAO)
    {
        __accDAO = accDAO;
    }

    /**
     * Add or update an account
     * @param account
     * @param password
     * @param level
     * @return the new account
     * @throws AccountModificationException 
     */
    public Accounts addOrUpdateAccount(String account, String password, String level) throws AccountModificationException
    {
        // o initialization
        // ---------------
        Accounts acc = null;

        // o Encode Password
        // ----------------
        MessageDigest md;
        byte[] newpass;
        try
        {
            md = MessageDigest.getInstance("SHA");
            newpass = password.getBytes("UTF-8");
            newpass = md.digest(newpass);
        }
        catch (NoSuchAlgorithmException e1)
        {
            throw new AccountModificationException("No algorithm to encode password.", e1);
        }
        catch (UnsupportedEncodingException e1)
        {
            throw new AccountModificationException("Unsupported encoding.", e1);
        }

        // o update account
        // ---------------
        try
        {
            acc = new Accounts();
            Integer iLevel = new Integer(level);
            acc.setLogin(account);
            acc.setAccessLevel(iLevel);
            acc.setPassword(Base64.encodeBytes(newpass));
            __accDAO.createOrUpdate(acc);
            if (_log.isDebugEnabled())
                _log.info("Account " + account + " has been updated.");
        }
        catch (NumberFormatException e)
        {
            throw new AccountModificationException("Error : level (" + level + ") should be an integer.", e);
        }
        return acc;
    }

    /**
     * Add or update an account
     * @param account
     * @return the new account
     * @throws AccountModificationException 
     */
    public Accounts addOrUpdateAccount(Accounts acc) throws AccountModificationException
    {
        // o update account
        // ---------------
        try
        {
            __accDAO.createOrUpdate(acc);
            if (_log.isDebugEnabled())
                _log.info("Account " + acc.getLogin() + " has been updated.");
        }
        catch (DataAccessException e)
        {
            throw new AccountModificationException("Unable to create account.", e);
        }
        return acc;
    }

    /**
     * Change account level
     * @param account - the account to upadte
     * @param level - the new level
     * @throws AccountModificationException
     */
    public void changeAccountLevel(String account, String level) throws AccountModificationException
    {
        // Search account
        // ---------------
        Accounts acc = __accDAO.getAccountById(account);

        if (acc == null)
            throw new AccountModificationException("Account " + account + " doesn't exist.");

        // Update account
        // --------------
        try
        {
            Integer iLevel = new Integer(level);
            acc.setAccessLevel(iLevel);
            __accDAO.createOrUpdate(acc);
            if (_log.isDebugEnabled())
                _log.debug("Account " + account + " has been updated.");
        }
        catch (NumberFormatException e)
        {
            throw new AccountModificationException("Error : level (" + level + ") should be an integer.", e);
        }
    }

    /**
     * Change account level
     * @param account - the account to upadte
     * @param level - the new level
     * @throws AccountModificationException
     */
    public void changeAccountLevel(String account, int level) throws AccountModificationException
    {
        // Search account
        // ---------------
        Accounts acc = __accDAO.getAccountById(account);

        if (acc == null)
            throw new AccountModificationException("Account " + account + " doesn't exist.");

        // Update account
        // --------------
        Integer iLevel = new Integer(level);
        acc.setAccessLevel(iLevel);
        __accDAO.update(acc);
        if (_log.isDebugEnabled())
            _log.debug("Account " + account + " has been updated.");
    }

    /**
     * Delete account and all linked objects
     * @param account
     * @throws AccountModificationException if account doest not exist
     */
    public void deleteAccount(String account) throws AccountModificationException
    {
        // Search and delete account
        // ---------------
        Accounts acc = null;
        try
        {
            acc = __accDAO.getAccountById(account);
        }
        catch (ObjectRetrievalFailureException e)
        {
            throw new AccountModificationException("Error : unable to delete account : " + account + ". This account does not exist.");
        }
        __accDAO.removeAccount(acc);
    }

    /**
     * Get accounts information
     *
     */
    public List<Accounts> getAccountsInfo()
    {
        List<Accounts> list = __accDAO.getAllAccounts();
        return list;
    }

    /**
     * Get account information for a specific id
     * 
     */
    public Accounts getAccountById(String id)
    {
        try
        {
            Accounts acc = __accDAO.getAccountById(id);
            return acc;
        }
        catch (ObjectRetrievalFailureException e)
        {
            _log.warn(e.getMessage());
            return null;
        }
        catch (Exception e)
        {
            _log.warn("The account [" + id + "] was not found in account table." + e.getMessage());
            return null;
        }
    }

}


PM MAIL ICQ Skype   Вверх
rygel
Дата 6.1.2009, 14:04 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 110
Регистрация: 21.9.2007
Где: Харьков

Репутация: 6
Всего: 7



в методе addOrUpdateAccount(String account, String password, String level)

замените

Код

byte[] newpass;
        try
        {
            md = MessageDigest.getInstance("SHA");
            newpass = password.getBytes("UTF-8");
            newpass = md.digest(newpass);
        }
        catch (NoSuchAlgorithmException e1)
        {
            throw new AccountModificationException("No algorithm to encode password.", e1);
        }
        catch (UnsupportedEncodingException e1)
        {
            throw new AccountModificationException("Unsupported encoding.", e1);
        }


на 

Код

  byte[] newpass;
        try
        {
            newpass = password.getBytes("UTF-8");
        }
        catch (UnsupportedEncodingException e1)
        {
            throw new AccountModificationException("Unsupported encoding.", e1);
        }


Это сообщение отредактировал(а) rygel - 6.1.2009, 14:05
PM MAIL   Вверх
Sobstvennaya
Дата 6.1.2009, 16:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 20
Регистрация: 31.12.2008

Репутация: нет
Всего: нет



Щас попробуемС.
PM MAIL ICQ Skype   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0490 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.