View Javadoc
1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.wss4j.common.derivedKey;
20  
21  import java.nio.charset.StandardCharsets;
22  
23  import org.apache.wss4j.common.ext.WSSecurityException;
24  
25  public final class DerivedKeyUtils {
26  
27      private DerivedKeyUtils() {
28          // complete
29      }
30  
31      /**
32       * Derive a key from this DerivedKeyToken instance
33       *
34       * @param length
35       * @param secret
36       * @throws org.apache.wss4j.stax.wss.ext.WSSecurityException
37       *
38       */
39      public static byte[] deriveKey(String algorithm, String label, int length, byte[] secret, byte[] nonce, int offset)
40          throws WSSecurityException {
41          DerivationAlgorithm algo = AlgoFactory.getInstance(algorithm);
42          byte[] labelBytes;
43          if (label == null || label.length() == 0) {
44              String defaultLabel = ConversationConstants.DEFAULT_LABEL + ConversationConstants.DEFAULT_LABEL;
45              labelBytes = defaultLabel.getBytes(StandardCharsets.UTF_8);
46          } else {
47              labelBytes = label.getBytes(StandardCharsets.UTF_8);
48          }
49  
50          byte[] seed = new byte[labelBytes.length + nonce.length];
51          System.arraycopy(labelBytes, 0, seed, 0, labelBytes.length);
52          System.arraycopy(nonce, 0, seed, labelBytes.length, nonce.length);
53  
54          long keyLength = length;
55          if (keyLength <= 0) {
56              keyLength = 32L;
57          }
58          return algo.createKey(secret, seed, offset, keyLength);
59      }
60  }