use of javax.crypto.interfaces.DHPrivateKey in project ofbiz-framework by apache.
the class ValueLinkApi method outputKeyCreation.
private StringBuffer outputKeyCreation(int loop, boolean kekOnly, String kekTest) {
StringBuffer buf = new StringBuffer();
loop++;
if (loop > 100) {
// only loop 100 times; then throw an exception
throw new IllegalStateException("Unable to create 128 byte keys in 100 tries");
}
// place holder for the keys
DHPrivateKey privateKey = null;
DHPublicKey publicKey = null;
if (!kekOnly) {
KeyPair keyPair = null;
try {
keyPair = this.createKeys();
} catch (NoSuchAlgorithmException e) {
Debug.logError(e, module);
} catch (InvalidAlgorithmParameterException e) {
Debug.logError(e, module);
} catch (InvalidKeySpecException e) {
Debug.logError(e, module);
}
if (keyPair != null) {
publicKey = (DHPublicKey) keyPair.getPublic();
privateKey = (DHPrivateKey) keyPair.getPrivate();
if (publicKey == null || publicKey.getY().toByteArray().length != 128) {
// run again until we get a 128 byte public key for VL
return this.outputKeyCreation(loop, kekOnly, kekTest);
}
} else {
Debug.logInfo("Returned a null KeyPair", module);
return this.outputKeyCreation(loop, kekOnly, kekTest);
}
} else {
// use our existing private key to generate a KEK
try {
privateKey = (DHPrivateKey) this.getPrivateKey();
} catch (Exception e) {
Debug.logError(e, module);
}
}
// the KEK
byte[] kekBytes = null;
try {
kekBytes = this.generateKek(privateKey);
} catch (NoSuchAlgorithmException e) {
Debug.logError(e, module);
} catch (InvalidKeySpecException e) {
Debug.logError(e, module);
} catch (InvalidKeyException e) {
Debug.logError(e, module);
}
// the 3DES KEK value
SecretKey loadedKek = this.getDesEdeKey(kekBytes);
byte[] loadKekBytes = loadedKek.getEncoded();
// test the KEK
Cipher cipher = this.getCipher(this.getKekKey(), Cipher.ENCRYPT_MODE);
byte[] kekTestB = { 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] kekTestC = new byte[0];
if (kekTest != null) {
kekTestB = StringUtil.fromHexString(kekTest);
}
// encrypt the test bytes
try {
kekTestC = cipher.doFinal(kekTestB);
} catch (Exception e) {
Debug.logError(e, module);
}
if (!kekOnly) {
// public key (just Y)
BigInteger y = publicKey.getY();
byte[] yBytes = y.toByteArray();
String yHex = StringUtil.toHexString(yBytes);
buf.append("======== Begin Public Key (Y @ ").append(yBytes.length).append(" / ").append(yHex.length()).append(") ========\n");
buf.append(yHex).append("\n");
buf.append("======== End Public Key ========\n\n");
// private key (just X)
BigInteger x = privateKey.getX();
byte[] xBytes = x.toByteArray();
String xHex = StringUtil.toHexString(xBytes);
buf.append("======== Begin Private Key (X @ ").append(xBytes.length).append(" / ").append(xHex.length()).append(") ========\n");
buf.append(xHex).append("\n");
buf.append("======== End Private Key ========\n\n");
// private key (full)
byte[] privateBytes = privateKey.getEncoded();
String privateHex = StringUtil.toHexString(privateBytes);
buf.append("======== Begin Private Key (Full @ ").append(privateBytes.length).append(" / ").append(privateHex.length()).append(") ========\n");
buf.append(privateHex).append("\n");
buf.append("======== End Private Key ========\n\n");
}
if (kekBytes != null) {
buf.append("======== Begin KEK (").append(kekBytes.length).append(") ========\n");
buf.append(StringUtil.toHexString(kekBytes)).append("\n");
buf.append("======== End KEK ========\n\n");
buf.append("======== Begin KEK (DES) (").append(loadKekBytes.length).append(") ========\n");
buf.append(StringUtil.toHexString(loadKekBytes)).append("\n");
buf.append("======== End KEK (DES) ========\n\n");
buf.append("======== Begin KEK Test (").append(kekTestC.length).append(") ========\n");
buf.append(StringUtil.toHexString(kekTestC)).append("\n");
buf.append("======== End KEK Test ========\n\n");
} else {
Debug.logError("KEK came back empty", module);
}
return buf;
}
use of javax.crypto.interfaces.DHPrivateKey in project Zom-Android by zom.
the class OtrCryptoEngineImpl method generateDHKeyPair.
public KeyPair generateDHKeyPair() throws OtrCryptoException {
// Generate a AsymmetricCipherKeyPair using BC.
DHParameters dhParams = new DHParameters(MODULUS, GENERATOR, null, DH_PRIVATE_KEY_MINIMUM_BIT_LENGTH);
DHKeyGenerationParameters params = new DHKeyGenerationParameters(new SecureRandom(), dhParams);
DHKeyPairGenerator kpGen = new DHKeyPairGenerator();
kpGen.init(params);
AsymmetricCipherKeyPair pair = kpGen.generateKeyPair();
// Convert this AsymmetricCipherKeyPair to a standard JCE KeyPair.
DHPublicKeyParameters pub = (DHPublicKeyParameters) pair.getPublic();
DHPrivateKeyParameters priv = (DHPrivateKeyParameters) pair.getPrivate();
try {
KeyFactory keyFac = KeyFactory.getInstance("DH");
DHPublicKeySpec pubKeySpecs = new DHPublicKeySpec(pub.getY(), MODULUS, GENERATOR);
DHPublicKey pubKey = (DHPublicKey) keyFac.generatePublic(pubKeySpecs);
DHParameters dhParameters = priv.getParameters();
DHPrivateKeySpec privKeySpecs = new DHPrivateKeySpec(priv.getX(), dhParameters.getP(), dhParameters.getG());
DHPrivateKey privKey = (DHPrivateKey) keyFac.generatePrivate(privKeySpecs);
return new KeyPair(pubKey, privKey);
} catch (Exception e) {
throw new OtrCryptoException(e);
}
}
use of javax.crypto.interfaces.DHPrivateKey in project wycheproof by google.
the class DhTest method testKeyPair.
private void testKeyPair(KeyPair keyPair, int expectedKeySize) throws Exception {
DHPrivateKey priv = (DHPrivateKey) keyPair.getPrivate();
BigInteger p = priv.getParams().getP();
BigInteger g = priv.getParams().getG();
int keySize = p.bitLength();
assertEquals("wrong key size", expectedKeySize, keySize);
// Checks the key size of the private key.
// NIST SP 800-56A requires that x is in the range (1, q-1).
// Such a choice would require a full key validation. Since such a validation
// requires the value q (which is not present in the DH parameters) larger keys
// should be chosen to prevent attacks.
int minPrivateKeyBits = keySize / 2;
BigInteger x = priv.getX();
assertTrue(x.bitLength() >= minPrivateKeyBits - 32);
// TODO(bleichen): add tests for weak random number generators.
// Verify the DH parameters.
System.out.println("p=" + p.toString(16));
System.out.println("g=" + g.toString(16));
System.out.println("testKeyPairGenerator L=" + priv.getParams().getL());
// Basic parameter checks
assertTrue("Expecting g > 1", g.compareTo(BigInteger.ONE) > 0);
assertTrue("Expecting g < p - 1", g.compareTo(p.subtract(BigInteger.ONE)) < 0);
// Expecting p to be prime.
// No high certainty is needed, since this is a unit test.
assertTrue(p.isProbablePrime(4));
// The order of g should be a large prime divisor q of p-1.
// (see e.g. NIST SP 800-56A, section 5.5.1.1.)
// If the order of g is composite then the Decision Diffie Hellman assumption is
// not satisfied for the group generated by g. Moreover, attacks using Pohlig-Hellman
// might be feasible.
// A good way to achieve these requirements is to select a safe prime p (i.e. a prime
// where q=(p-1)/2 is prime too. NIST SP 800-56A does not require (or even recommend)
// safe primes and allows Diffie-Hellman parameters where q is significantly smaller.
// Unfortunately, the key does not contain q and thus the conditions above cannot be
// tested easily.
// We perform a partial test that performs a partial factorization of p-1 and then
// test whether one of the small factors found by the partial factorization divides
// the order of g.
boolean isSafePrime = p.shiftRight(1).isProbablePrime(4);
System.out.println("p is a safe prime:" + isSafePrime);
// p-1 divided by small prime factors.
BigInteger r;
if (isSafePrime) {
r = p.shiftRight(1);
} else {
BigInteger p1 = p.subtract(BigInteger.ONE);
r = p1.divide(smoothDivisor(p1));
}
System.out.println("r=" + r.toString(16));
assertEquals("g likely does not generate a prime oder subgroup", BigInteger.ONE, g.modPow(r, p));
// Checks that there are not too many short prime factors.
// I.e., subgroup confinment attacks can find at least keySize - r.bitLength() bits of the key.
// At least 160 unknown bits should remain.
// Only very weak parameters are detected here, since the factorization above only finds small
// prime factors.
assertTrue(minPrivateKeyBits - (keySize - r.bitLength()) > 160);
// A large g that divides p-1 is suspicious.
if (g.bitLength() >= 160) {
assertTrue(p.mod(g).compareTo(BigInteger.ONE) > 0);
}
}
use of javax.crypto.interfaces.DHPrivateKey in project Gradle-demo by Arisono.
the class DHUtil method initKey.
/**
* 甲方初始化并返回密钥对
*/
public static Map<String, Object> initKey() throws Exception {
// 实例化密钥对生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DH");
// 初始化密钥对生成器 默认是1024 512-1024 & 64的倍数
keyPairGenerator.initialize(1024);
// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 得到甲方公钥
DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
// 得到甲方私钥
DHPrivateKey peivateKey = (DHPrivateKey) keyPair.getPrivate();
// 将公钥和私钥封装到Map中,方便之后使用
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, peivateKey);
return keyMap;
}
use of javax.crypto.interfaces.DHPrivateKey in project robovm by robovm.
the class KeyAgreementSpi method engineInit.
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();
}
Aggregations