1 // 2 // ======================================================================== 3 // Copyright (c) 1995-2013 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.nio.charset.StandardCharsets; 23 import java.security.MessageDigest; 24 25 import org.eclipse.jetty.util.B64Code; 26 import org.eclipse.jetty.util.StringUtil; 27 28 /** 29 * Logic for working with the <code>Sec-WebSocket-Key</code> and <code>Sec-WebSocket-Accept</code> headers. 30 * <p> 31 * This is kept separate from Connection objects to facilitate difference in behavior between client and server, as well as making testing easier. 32 */ 33 public class AcceptHash 34 { 35 /** 36 * Globally Unique Identifier for use in WebSocket handshake within <code>Sec-WebSocket-Accept</code> and <code>Sec-WebSocket-Key</code> http headers. 37 * <p> 38 * See <a href="https://tools.ietf.org/html/rfc6455#section-1.3">Opening Handshake (Section 1.3)</a> 39 */ 40 private final static byte[] MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(StandardCharsets.ISO_8859_1); 41 42 /** 43 * Concatenate the provided key with the Magic GUID and return the Base64 encoded form. 44 * 45 * @param key 46 * the key to hash 47 * @return the <code>Sec-WebSocket-Accept</code> header response (per opening handshake spec) 48 */ 49 public static String hashKey(String key) 50 { 51 try 52 { 53 MessageDigest md = MessageDigest.getInstance("SHA1"); 54 md.update(key.getBytes(StandardCharsets.UTF_8)); 55 md.update(MAGIC); 56 return new String(B64Code.encode(md.digest())); 57 } 58 catch (Exception e) 59 { 60 throw new RuntimeException(e); 61 } 62 } 63 }