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