001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.openid.connect.sdk.id; 019 020 021import com.nimbusds.jose.util.Base64URL; 022import com.nimbusds.oauth2.sdk.id.Subject; 023import net.jcip.annotations.ThreadSafe; 024 025import java.security.MessageDigest; 026import java.security.NoSuchAlgorithmException; 027import java.util.Objects; 028 029 030/** 031 * SHA-256 based encoder of pairwise subject identifiers. Reversal is not 032 * supported. 033 * 034 * <p>Algorithm: 035 * 036 * <pre> 037 * sub = SHA-256 ( sector_id || local_sub || salt ) 038 * </pre> 039 * 040 * <p>Related specifications: 041 * 042 * <ul> 043 * <li>OpenID Connect Core 1.0 044 * </ul> 045 */ 046@ThreadSafe 047public class HashBasedPairwiseSubjectCodec extends PairwiseSubjectCodec { 048 049 050 /** 051 * The hashing algorithm. 052 */ 053 public static final String HASH_ALGORITHM = "SHA-256"; 054 055 056 /** 057 * Creates a new hash-based codec for pairwise subject identifiers. 058 * 059 * @param salt The salt, must not be {@code null}. 060 */ 061 public HashBasedPairwiseSubjectCodec(final byte[] salt) { 062 super(Objects.requireNonNull(salt)); 063 } 064 065 066 /** 067 * Creates a new hash-based codec for pairwise subject identifiers. 068 * 069 * @param salt The salt, must not be {@code null}. 070 */ 071 public HashBasedPairwiseSubjectCodec(final Base64URL salt) { 072 super(salt.decode()); 073 } 074 075 076 @Override 077 public Subject encode(final SectorID sectorID, final Subject localSub) { 078 079 MessageDigest sha256; 080 try { 081 if (getProvider() != null) { 082 sha256 = MessageDigest.getInstance(HASH_ALGORITHM, getProvider()); 083 } else { 084 sha256 = MessageDigest.getInstance(HASH_ALGORITHM); 085 } 086 } catch (NoSuchAlgorithmException e) { 087 throw new RuntimeException(e.getMessage(), e); 088 } 089 090 sha256.update(sectorID.getValue().getBytes(CHARSET)); 091 sha256.update(localSub.getValue().getBytes(CHARSET)); 092 byte[] hash = sha256.digest(getSalt()); 093 094 return new Subject(Base64URL.encode(hash).toString()); 095 } 096}