001package com.nimbusds.openid.connect.sdk; 002 003 004import net.jcip.annotations.Immutable; 005 006import org.apache.commons.lang3.StringUtils; 007 008import com.nimbusds.oauth2.sdk.id.Identifier; 009 010 011/** 012 * Nonce. This is a random, unique string value to associate a user-session 013 * with an ID Token and to mitigate replay attacks. This class is immutable. 014 * 015 * <p>Example generation of a nonce with eight random mixed-case alphanumeric 016 * characters: 017 * 018 * <pre> 019 * Nonce nonce = new Nonce(8); 020 * </pre> 021 * 022 * <p>Related specifications: 023 * 024 * <ul> 025 * <li>OpenID Connect Messages 1.0, section 2.1.1 and 2.1.2.1. 026 * </ul> 027 * 028 * @author Vladimir Dzhuvinov 029 */ 030@Immutable 031public final class Nonce extends Identifier { 032 033 034 /** 035 * Creates a new nonce with the specified value. 036 * 037 * @param value The nonce value. Must not be {@code null} or empty 038 * string. 039 */ 040 public Nonce(final String value) { 041 042 super(value); 043 } 044 045 046 /** 047 * Creates a new nonce with a randomly generated value of the specified 048 * byte length, Base64URL-encoded. 049 * 050 * @param byteLength The byte length of the value to generate. Must be 051 * greater than one. 052 */ 053 public Nonce(final int byteLength) { 054 055 super(byteLength); 056 } 057 058 059 /** 060 * Creates a new nonce with a randomly generated 256-bit (32-byte) 061 * value, Base64URL-encoded. 062 */ 063 public Nonce() { 064 065 super(); 066 } 067 068 069 @Override 070 public boolean equals(final Object object) { 071 072 return object instanceof Nonce && 073 this.toString().equals(object.toString()); 074 } 075 076 077 /** 078 * Parses a nonce from the specified string. 079 * 080 * @param s The string to parse, {@code null} or empty if no nonce is 081 * specified. 082 * 083 * @return The nonce, {@code null} if the parsed string was 084 * {@code null} or empty. 085 */ 086 public static Nonce parse(final String s) { 087 088 if (StringUtils.isBlank(s)) 089 return null; 090 091 return new Nonce(s); 092 } 093}