下面列出了javax.crypto.spec.DHParameterSpec#getG() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec");
}
DHParameterSpec dhParams = (DHParameterSpec)params;
param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));
engine.init(param);
initialised = true;
}
public void initialize(
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
if (!(params instanceof ElGamalParameterSpec) && !(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec or an ElGamalParameterSpec");
}
if (params instanceof ElGamalParameterSpec)
{
ElGamalParameterSpec elParams = (ElGamalParameterSpec)params;
param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(elParams.getP(), elParams.getG()));
}
else
{
DHParameterSpec dhParams = (DHParameterSpec)params;
param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
}
engine.init(param);
initialised = true;
}
protected void engineInit(
AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (!(paramSpec instanceof ElGamalParameterSpec) && !(paramSpec instanceof DHParameterSpec))
{
throw new InvalidParameterSpecException("DHParameterSpec required to initialise a ElGamal algorithm parameters object");
}
if (paramSpec instanceof ElGamalParameterSpec)
{
this.currentSpec = (ElGamalParameterSpec)paramSpec;
}
else
{
DHParameterSpec s = (DHParameterSpec)paramSpec;
this.currentSpec = new ElGamalParameterSpec(s.getP(), s.getG());
}
}
/**
* Get a public key object for the ValueLink supplied public key
* @return PublicKey object of ValueLinks's public key
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public PublicKey getValueLinkPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// read the valuelink public key
String publicValue = (String) props.get("payment.valuelink.publicValue");
byte[] publicKeyBytes = StringUtil.fromHexString(publicValue);
// initialize the parameter spec
DHParameterSpec dhParamSpec = this.getDHParameterSpec();
// load the valuelink public key
KeyFactory keyFactory = KeyFactory.getInstance("DH");
BigInteger publicKeyInt = new BigInteger(publicKeyBytes);
DHPublicKeySpec dhPublicSpec = new DHPublicKeySpec(publicKeyInt, dhParamSpec.getP(), dhParamSpec.getG());
PublicKey vlPublic = keyFactory.generatePublic(dhPublicSpec);
return vlPublic;
}
public KeyPair generateKeyPair()
{
if (!initialised)
{
DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);
if (dhParams != null)
{
param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
}
else
{
ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();
pGen.init(strength, certainty, random);
param = new ElGamalKeyGenerationParameters(random, pGen.generateParameters());
}
engine.init(param);
initialised = true;
}
AsymmetricCipherKeyPair pair = engine.generateKeyPair();
ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters)pair.getPrivate();
return new KeyPair(new BCElGamalPublicKey(pub),
new BCElGamalPrivateKey(priv));
}
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
if (key instanceof DHPublicKey) {
DHPublicKey dhKey = (DHPublicKey)key;
DHParameterSpec params = dhKey.getParams();
return new DHPublicKeySpec(dhKey.getY(),
params.getP(), params.getG());
}
try {
KeyFactory factory = JsseJce.getKeyFactory("DiffieHellman");
return factory.getKeySpec(key, DHPublicKeySpec.class);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// unlikely
throw new RuntimeException("Unable to get DHPublicKeySpec", e);
}
}
/**
* 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);
}
public KeyPair generateKeyPair()
{
if (!initialised)
{
DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);
if (dhParams != null)
{
param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL()));
}
else
{
ElGamalParametersGenerator pGen = new ElGamalParametersGenerator();
pGen.init(strength, certainty, random);
param = new ElGamalKeyGenerationParameters(random, pGen.generateParameters());
}
engine.init(param);
initialised = true;
}
AsymmetricCipherKeyPair pair = engine.generateKeyPair();
ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters)pair.getPublic();
ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters)pair.getPrivate();
return new KeyPair(new BCElGamalPublicKey(pub),
new BCElGamalPrivateKey(priv));
}
private static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
if (key instanceof DHPublicKey) {
DHPublicKey dhKey = (DHPublicKey)key;
DHParameterSpec params = dhKey.getParams();
return new DHPublicKeySpec(dhKey.getY(),
params.getP(), params.getG());
}
try {
KeyFactory factory = KeyFactory.getInstance("DiffieHellman");
return factory.getKeySpec(key, DHPublicKeySpec.class);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// unlikely
throw new RuntimeException("Unable to get DHPublicKeySpec", e);
}
}
protected void engineInit(
Key key,
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
if (!(key instanceof DHPrivateKey))
{
throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation");
}
DHPrivateKey privKey = (DHPrivateKey)key;
if (params != null)
{
if (!(params instanceof DHParameterSpec))
{
throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec");
}
DHParameterSpec p = (DHParameterSpec)params;
this.p = p.getP();
this.g = p.getG();
}
else
{
this.p = privKey.getParams().getP();
this.g = privKey.getParams().getG();
}
this.x = this.result = privKey.getX();
}
/**
* 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);
}
/**
* 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);
}
/**
* Get merchant Private Key
* @return PrivateKey object for the merchant
*/
public PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
byte[] privateKeyBytes = this.getPrivateKeyBytes();
// initialize the parameter spec
DHParameterSpec dhParamSpec = this.getDHParameterSpec();
// load the private key
KeyFactory keyFactory = KeyFactory.getInstance("DH");
BigInteger privateKeyInt = new BigInteger(privateKeyBytes);
DHPrivateKeySpec dhPrivateSpec = new DHPrivateKeySpec(privateKeyInt, dhParamSpec.getP(), dhParamSpec.getG());
PrivateKey privateKey = keyFactory.generatePrivate(dhPrivateSpec);
return privateKey;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* Tests whether a provider accepts invalid public keys that result in predictable shared secrets.
* This test is based on RFC 2785, Section 4 and NIST SP 800-56A, If an attacker can modify both
* public keys in an ephemeral-ephemeral key agreement scheme then it may be possible to coerce
* both parties into computing the same predictable shared key.
*
* <p>Note: the test is quite whimsical. If the prime p is not a safe prime then the provider
* itself cannot prevent all small-subgroup attacks because of the missing parameter q in the
* Diffie-Hellman parameters. Implementations must add additional countermeasures such as the ones
* proposed in RFC 2785.
*
* <p>CVE-2016-1000346: BouncyCastle before v.1.56 did not validate the other parties public key.
*/
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testSubgroupConfinement() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
DHParameterSpec params = ike2048();
BigInteger p = params.getP();
BigInteger g = params.getG();
keyGen.initialize(params);
PrivateKey priv = keyGen.generateKeyPair().getPrivate();
KeyAgreement ka = KeyAgreement.getInstance("DH");
BigInteger[] weakPublicKeys = {
BigInteger.ZERO,
BigInteger.ONE,
p.subtract(BigInteger.ONE),
p,
p.add(BigInteger.ONE),
BigInteger.ONE.negate()
};
for (BigInteger weakKey : weakPublicKeys) {
ka.init(priv);
try {
KeyFactory kf = KeyFactory.getInstance("DH");
DHPublicKeySpec weakSpec = new DHPublicKeySpec(weakKey, p, g);
PublicKey pub = kf.generatePublic(weakSpec);
ka.doPhase(pub, true);
byte[] kAB = ka.generateSecret();
fail(
"Generated secrets with weak public key:"
+ weakKey.toString()
+ " secret:"
+ TestUtil.bytesToHex(kAB));
} catch (GeneralSecurityException ex) {
// this is expected
}
}
}
/**
* 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);
}
@Override
public void consume(ConnectionContext context,
ByteBuffer message) throws IOException {
// The consuming happens in server side only.
ServerHandshakeContext shc = (ServerHandshakeContext)context;
DHEPossession dhePossession = null;
for (SSLPossession possession : shc.handshakePossessions) {
if (possession instanceof DHEPossession) {
dhePossession = (DHEPossession)possession;
break;
}
}
if (dhePossession == null) {
// unlikely
throw shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
"No expected DHE possessions for client key exchange");
}
SSLKeyExchange ke = SSLKeyExchange.valueOf(
shc.negotiatedCipherSuite.keyExchange,
shc.negotiatedProtocol);
if (ke == null) {
// unlikely
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
"Not supported key exchange type");
}
DHClientKeyExchangeMessage ckem =
new DHClientKeyExchangeMessage(shc, message);
if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) {
SSLLogger.fine(
"Consuming DH ClientKeyExchange handshake message", ckem);
}
// create the credentials
try {
DHParameterSpec params = dhePossession.publicKey.getParams();
DHPublicKeySpec spec = new DHPublicKeySpec(
new BigInteger(1, ckem.y),
params.getP(), params.getG());
KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
DHPublicKey peerPublicKey =
(DHPublicKey)kf.generatePublic(spec);
// check constraints of peer DHPublicKey
if (!shc.algorithmConstraints.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
peerPublicKey)) {
throw new SSLHandshakeException(
"DHPublicKey does not comply to algorithm constraints");
}
NamedGroup namedGroup = NamedGroup.valueOf(params);
shc.handshakeCredentials.add(
new DHECredentials(peerPublicKey, namedGroup));
} catch (GeneralSecurityException | java.io.IOException e) {
throw (SSLHandshakeException)(new SSLHandshakeException(
"Could not generate DHPublicKey").initCause(e));
}
// update the states
SSLKeyDerivation masterKD = ke.createKeyDerivation(shc);
SecretKey masterSecret =
masterKD.deriveKey("MasterSecret", null);
shc.handshakeSession.setMasterSecret(masterSecret);
SSLTrafficKeyDerivation kd =
SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol);
if (kd == null) {
// unlikely
throw shc.conContext.fatal(Alert.INTERNAL_ERROR,
"Not supported key derivation: " + shc.negotiatedProtocol);
} else {
shc.handshakeKeyDerivation =
kd.createKeyDerivation(shc, masterSecret);
}
}
public KeyPair generateKeyPair()
{
if (!initialised)
{
Integer paramStrength = Integers.valueOf(strength);
if (params.containsKey(paramStrength))
{
param = (DHKeyGenerationParameters)params.get(paramStrength);
}
else
{
DHParameterSpec dhParams = BouncyCastleProvider.CONFIGURATION.getDHDefaultParameters(strength);
if (dhParams != null)
{
param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL()));
}
else
{
synchronized (lock)
{
// we do the check again in case we were blocked by a generator for
// our key size.
if (params.containsKey(paramStrength))
{
param = (DHKeyGenerationParameters)params.get(paramStrength);
}
else
{
DHParametersGenerator pGen = new DHParametersGenerator();
pGen.init(strength, certainty, random);
param = new DHKeyGenerationParameters(random, pGen.generateParameters());
params.put(paramStrength, param);
}
}
}
}
engine.init(param);
initialised = true;
}
AsymmetricCipherKeyPair pair = engine.generateKeyPair();
DHPublicKeyParameters pub = (DHPublicKeyParameters)pair.getPublic();
DHPrivateKeyParameters priv = (DHPrivateKeyParameters)pair.getPrivate();
return new KeyPair(new BCDHPublicKey(pub),
new BCDHPrivateKey(priv));
}