Hessian 인터페이스 호출 시 DSA 암호 화

7548 단어 springbean
저 희 는 hessian 인 터 페 이 스 를 자주 사용 합 니 다. 그러나 hessian 인 터 페 이 스 는 기본 적 인 상황 에서 암호 화 되 지 않 습 니 다. 원래 프로젝트 에서 MD5 의 암호 화 를 사 용 했 습 니 다. 이번 에는 DSA 암호 화 를 통 해 C - S 의 안전 통신 을 해결 하고 자 합 니 다. 한편 으로 는 클 라 이언 트 가 호출 권한 이 있 는 지 확인 하고 전송 하 는 데이터 안전 을 보장 합 니 다.
 
  기본 적 인 사 고 는 새로운 Hessian Proxy Factory 와 Hessian ServiceExporter 를 사용 하여 원래 의 발송 과 수신 단 을 대체 하고 요청 을 보 낼 때 비밀 키 암호 화 를 하고 받 을 때 공개 키 의 복호화 를 하 는 것 이다.
 
  기본 논 리 는 다음 과 같다.
 
/**
 *         hessian client
 * 
 * <pre>
 *   spring hessian  ,  DSAHessianProxyFactory     HessianProxyFactory
 * &lt;bean id=&quot;heessianClient&quot; class=&quot;org.springframework.remoting.caucho.HessianProxyFactoryBean&quot;&gt;
 *      &lt;property name=&quot;proxyFactory&quot;&gt;
 *          &lt;bean class=&quot;com.alibaba.pivot.common.hessian.DSAHessianProxyFactory&quot;&gt;
 *              &lt;property name=&quot;secureKey&quot; value=&quot;xxxxx&quot;/&gt;
 *          &lt;/bean&gt;
 *      &lt;/property&gt;
 * &lt;/bean&gt;
 * </pre>
 * 
 * @author job 2010-01-28   10:20:01
 */
public class DSAHessianProxyFactory extends HessianProxyFactory {

    private static final Logger log = LoggerFactory.getLogger(DSAHessianProxyFactory.class);

    private DSAService          dsaService;

    private String     keyPairName;

    /**
     *         
     */
    private String              secureKey;

    protected URLConnection openConnection(URL url) throws IOException {
        String signature = null;
        String baseUrl = url.toString();
        StringBuilder queryBuilder = new StringBuilder();
        queryBuilder.append(baseUrl);

        //      
        long timestamp = System.currentTimeMillis();
        //       
        try {
            signature = dsaService.sign(secureKey + "|" + Long.toString(timestamp), keyPairName);
        } catch (NoSuchKeyPairException ne) {
            log.error("error in DSAHessianProxyFactory.openConnection,no such key" + keyPairName, ne);
        } catch (DSAException de) {
            log.error("error in DSAHessianProxyFactory.openConnection,DSA sign error" + keyPairName, de);
        }
        if (!"?".equals(queryBuilder.charAt(queryBuilder.length() - 1))) {
            queryBuilder.append("?");
        }

        queryBuilder.append("sign=");
        if (signature != null) {
            queryBuilder.append(StringEscapeUtil.escapeURL(signature));
        }
        queryBuilder.append("&time=");
        queryBuilder.append(timestamp);
        URL secureUrl = new URL(queryBuilder.toString());

        URLConnection conn = secureUrl.openConnection();

        conn.setDoOutput(true);

        if (getReadTimeout() > 0) {
            try {
                conn.setReadTimeout((int) getReadTimeout());
            } catch (Throwable e) {
            }
        }
        //       content-type
        conn.setRequestProperty("Content-Type", "application/octet-stream");

        return conn;
    }

 
 
 
출력 할 때의 암호 화:
 
/**
 *      hessian server,     pivot-p4p
 * 
 * <pre>
 * 1. timeout       ,   . (               ,       ,                    )
 * 2. secureKey        (       ,                 )
 * 3. allowedClients    IP   (       ,          IP    )
 * </pre>
 * 
 * @author job 2010-01-28   09:53:02
 */
public class DSAHessianServiceExporter extends HessianServiceExporter {

    private static Logger log = LoggerFactory.getLogger(DSAHessianServiceExporter.class);

    /**        **/
    private long          timeout;
    /**      **/
    private String        secureKey;
    /**          **/
    private String        allowedClients;
    /** dsa      **/
    private DSAService    dsaService;
    /**      **/
    private String        keyPairName;

    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       IOException {
        // 1.        IP  ,       IP    
        if (StringUtil.isNotBlank(allowedClients)) {
            String clientIP = getClientIPAddress(request);
            if (!isAllowedClient(clientIP)) {
                log.error("hessian authentication error:" + clientIP + " not in allowedList " + allowedClients);
                return;
            }
        }

        // 2.             ,            
        String strTimestamp = request.getParameter("time");
        long timestamp = 0;
        if (timeout > 0 || StringUtil.isNotBlank(secureKey)) {
            if (strTimestamp == null) {
                log.error("hessian authentication error:timestamp not exist!");
                return;
            }
            try {
                timestamp = Long.parseLong(strTimestamp);
            } catch (NumberFormatException e) {
                log.error("hessian authentication error:timestamp is not number!");
                return;
            }
        }

        // 3.         ,          
        if (timeout > 0) {
            //         
            if (isRequestExpired(timestamp)) {
                log.error("hessian authentication error:request is expired!");
                return;
            }
        }

        // 4.        ,        
        if (StringUtil.isNotBlank(secureKey)) {
            // 4.1     
            String signature = request.getParameter("sign");
            if (signature == null) {
                log.error("hessian authentication error:signatures not exist!");
                return;
            }
            try {
                // 4.2         
                boolean isRight = dsaService.check(secureKey + "|" + timestamp, signature, keyPairName);
                if (!isRight) {
                    log.error("hessian authentication error:signatures not match!");
                    return;
                }
            } catch (NoSuchKeyPairException ne) {
                log.error("error in DSAHessianServiceExporter.handleRequest,no such key" + keyPairName, ne);
            } catch (DSAException de) {
                log.error("error in DSAHessianServiceExporter.handleRequest,DSA sign error", de);
            }

        }
        // 5.   hessian context-type
        response.setContentType("application/octet-stream");
        super.handleRequest(request, response);
    }

 
 
 
 
키 의 생 성에 대해 서 는 자바 가 가지 고 있 는 도구 인 키스 토어 로 생 성 할 수 있 습 니 다.

좋은 웹페이지 즐겨찾기