Java examples for Security:Key
Returns whether the Diffie-Hellman public key is valid or not.
/*// ww w.j av a 2 s.c om * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ //package com.java2s; import java.security.InvalidKeyException; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; import java.math.BigInteger; public class Main { /** * Returns whether the Diffie-Hellman public key is valid or not. * * Per RFC 2631 and NIST SP800-56A, the following algorithm is used to * validate Diffie-Hellman public keys: * 1. Verify that y lies within the interval [2,p-1]. If it does not, * the key is invalid. * 2. Compute y^q mod p. If the result == 1, the key is valid. * Otherwise the key is invalid. */ private static void validateDHPublicKey(DHPublicKey publicKey) throws InvalidKeyException { DHParameterSpec paramSpec = publicKey.getParams(); BigInteger p = paramSpec.getP(); BigInteger g = paramSpec.getG(); BigInteger y = publicKey.getY(); validateDHPublicKey(p, g, y); } private static void validateDHPublicKey(DHPublicKeySpec publicKeySpec) throws InvalidKeyException { validateDHPublicKey(publicKeySpec.getP(), publicKeySpec.getG(), publicKeySpec.getY()); } private static void validateDHPublicKey(BigInteger p, BigInteger g, BigInteger y) throws InvalidKeyException { // For better interoperability, the interval is limited to [2, p-2]. BigInteger leftOpen = BigInteger.ONE; BigInteger rightOpen = p.subtract(BigInteger.ONE); if (y.compareTo(leftOpen) <= 0) { throw new InvalidKeyException( "Diffie-Hellman public key is too small"); } if (y.compareTo(rightOpen) >= 0) { throw new InvalidKeyException( "Diffie-Hellman public key is too large"); } // Don't bother to check against the y^q mod p if safe primes are used. } }