1 //
2 // ========================================================================
3 // Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.websocket.common;
20
21 import java.io.UnsupportedEncodingException;
22 import java.security.MessageDigest;
23
24 import org.eclipse.jetty.util.B64Code;
25 import org.eclipse.jetty.util.StringUtil;
26
27 /**
28 * Logic for working with the <code>Sec-WebSocket-Key</code> and <code>Sec-WebSocket-Accept</code> headers.
29 * <p>
30 * This is kept separate from Connection objects to facilitate difference in behavior between client and server, as well as making testing easier.
31 */
32 public class AcceptHash
33 {
34 /**
35 * Globally Unique Identifier for use in WebSocket handshake within <code>Sec-WebSocket-Accept</code> and <code>Sec-WebSocket-Key</code> http headers.
36 * <p>
37 * See <a href="https://tools.ietf.org/html/rfc6455#section-1.3">Opening Handshake (Section 1.3)</a>
38 */
39 private final static byte[] MAGIC;
40
41 static
42 {
43 try
44 {
45 MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(StringUtil.__ISO_8859_1);
46 }
47 catch (UnsupportedEncodingException e)
48 {
49 throw new RuntimeException(e);
50 }
51 }
52
53 /**
54 * Concatenate the provided key with the Magic GUID and return the Base64 encoded form.
55 *
56 * @param key
57 * the key to hash
58 * @return the <code>Sec-WebSocket-Accept</code> header response (per opening handshake spec)
59 */
60 public static String hashKey(String key)
61 {
62 try
63 {
64 MessageDigest md = MessageDigest.getInstance("SHA1");
65 md.update(key.getBytes("UTF-8"));
66 md.update(MAGIC);
67 return new String(B64Code.encode(md.digest()));
68 }
69 catch (Exception e)
70 {
71 throw new RuntimeException(e);
72 }
73 }
74 }