Search in sources :

Example 1 with AsymmetricCipherKeyPair

use of org.spongycastle.crypto.AsymmetricCipherKeyPair in project rskj by rsksmart.

the class CryptoTest method test14.

// ECIES_AES128_SHA256 + No Ephemeral Key + IV(all zeroes)
@Test
public void test14() throws Throwable {
    AESFastEngine aesFastEngine = new AESFastEngine();
    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);
    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    eGen.init(gParam);
    AsymmetricCipherKeyPair p1 = eGen.generateKeyPair();
    AsymmetricCipherKeyPair p2 = eGen.generateKeyPair();
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);
    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));
    iesEngine.init(true, p1.getPrivate(), p2.getPublic(), parametersWithIV);
    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));
    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));
    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine)));
    decryptorIES_Engine.init(false, p2.getPrivate(), p1.getPublic(), parametersWithIV);
    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);
    log.info("orig: " + Hex.toHexString(orig));
}
Also used : ECKeyPairGenerator(org.spongycastle.crypto.generators.ECKeyPairGenerator) HMac(org.spongycastle.crypto.macs.HMac) SecureRandom(java.security.SecureRandom) SICBlockCipher(org.spongycastle.crypto.modes.SICBlockCipher) AESFastEngine(org.spongycastle.crypto.engines.AESFastEngine) KeyGenerationParameters(org.spongycastle.crypto.KeyGenerationParameters) IESEngine(org.spongycastle.crypto.engines.IESEngine) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) ECDHBasicAgreement(org.spongycastle.crypto.agreement.ECDHBasicAgreement) KDF2BytesGenerator(org.spongycastle.crypto.generators.KDF2BytesGenerator) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) BufferedBlockCipher(org.spongycastle.crypto.BufferedBlockCipher) Test(org.junit.Test)

Example 2 with AsymmetricCipherKeyPair

use of org.spongycastle.crypto.AsymmetricCipherKeyPair 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);
    }
}
Also used : DHPrivateKey(javax.crypto.interfaces.DHPrivateKey) KeyPair(java.security.KeyPair) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) DHPublicKeyParameters(org.spongycastle.crypto.params.DHPublicKeyParameters) DHParameters(org.spongycastle.crypto.params.DHParameters) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHPrivateKeyParameters(org.spongycastle.crypto.params.DHPrivateKeyParameters) DHKeyGenerationParameters(org.spongycastle.crypto.params.DHKeyGenerationParameters) SecureRandom(java.security.SecureRandom) DHKeyPairGenerator(org.spongycastle.crypto.generators.DHKeyPairGenerator) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) DHPrivateKeySpec(javax.crypto.spec.DHPrivateKeySpec) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyFactory(java.security.KeyFactory)

Example 3 with AsymmetricCipherKeyPair

use of org.spongycastle.crypto.AsymmetricCipherKeyPair in project SightRemote by TebbeUbben.

the class Cryptograph method generateRSAKey.

public static KeyPair generateRSAKey() {
    RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
    generator.init(new RSAKeyGenerationParameters(BigInteger.valueOf(65537), new SecureRandom(), 2048, 8));
    AsymmetricCipherKeyPair ackp = generator.generateKeyPair();
    KeyPair keyPair = new KeyPair();
    keyPair.privateKey = (RSAPrivateCrtKeyParameters) ackp.getPrivate();
    keyPair.publicKey = (RSAKeyParameters) ackp.getPublic();
    return keyPair;
}
Also used : AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) RSAKeyPairGenerator(org.spongycastle.crypto.generators.RSAKeyPairGenerator) SecureRandom(java.security.SecureRandom) RSAKeyGenerationParameters(org.spongycastle.crypto.params.RSAKeyGenerationParameters) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair)

Example 4 with AsymmetricCipherKeyPair

use of org.spongycastle.crypto.AsymmetricCipherKeyPair in project universa by UniversaBlockchain.

the class OAEPEncodingTest method randomEncodeDecode.

/**
 * Make sure the SpongyCastle OAEPEncoding encoding and decoding operations
 * do not lose or corrupt data.
 * We test it:
 * For each hash function we may use with OEAP (like, SHA1 or SHA512),
 * and for each RSA key size (among 1024, 2048, 4096)
 * we create multiple (NUMBER_OF_RANDOM_ENCRYPTION_KEY_PAIRS) RSA key pairs;
 * for each of the key pair we test encryption-decryption cycle
 * with NUMBER_OF_RANDOM_ENCRYPTION_DECRYPTION_CYCLES_PER_KEY_PAIR random messages
 * (each of the maximum possible size for this cipher configuration)
 * and make sure the result matches the original random message.
 *
 * @throws Exception
 */
@Test
public void randomEncodeDecode() throws Exception {
    RSAKeyPairGenerator keyGen = new RSAKeyPairGenerator();
    for (Digest digest : DIGESTS) {
        for (int i = 0; i < NUMBER_OF_RANDOM_ENCRYPTION_KEY_PAIRS; i++) {
            // Create key pair
            SecureRandom rng = new SecureRandom();
            int publicExponent = PUBLIC_EXPONENTS[rng.nextInt(PUBLIC_EXPONENTS.length)];
            int keySize = KEY_SIZES[rng.nextInt(KEY_SIZES.length)];
            keyGen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(publicExponent), new SecureRandom(), keySize, RSA_KEY_CERTAINTY));
            AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair();
            RSAKeyParameters publicKey = (RSAKeyParameters) keyPair.getPublic(), privateKey = (RSAKeyParameters) keyPair.getPrivate();
            assertEquals(keySize, publicKey.getModulus().bitLength());
            // though actually it is sufficient to keysize <= publicKey.getModulus().bitLength()
            int maxMessageSize = keySize / 8 - 2 - 2 * digest.getDigestSize(), minMessageSize = 1, messageSize = (maxMessageSize >= minMessageSize) ? rng.nextInt(maxMessageSize - minMessageSize + 1) + minMessageSize : 0;
            // messageSize may become negative with too small RSA key size and too large digest.
            if (messageSize > 0) {
                // For each key pair we do multiple encryption-decryption cycles
                for (int j = 0; j < NUMBER_OF_RANDOM_ENCRYPTION_DECRYPTION_CYCLES_PER_KEY_PAIR; j++) {
                    // Create random message
                    byte[] message = new byte[messageSize];
                    rng.nextBytes(message);
                    AsymmetricBlockCipher encoder = new OAEPEncoding(RSAEngineFactory.make(), digest), decoder = new OAEPEncoding(RSAEngineFactory.make(), digest);
                    encoder.init(true, publicKey);
                    decoder.init(false, privateKey);
                    byte[] encoded = encoder.processBlock(message, 0, message.length);
                    byte[] decoded = decoder.processBlock(encoded, 0, encoded.length);
                    // Finally, test the encoding/decoding cycle
                    String assertMessage = String.format("Digest %s,\n message %s,\n public key %s / %s,\n private key %s / %s", digest, Hex.toHexString(message), publicKey.getExponent(), publicKey.getModulus(), privateKey.getExponent(), privateKey.getModulus());
                    assertArrayEquals(assertMessage, message, decoded);
                }
            }
        }
    }
}
Also used : Digest(org.spongycastle.crypto.Digest) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) SHA1Digest(org.spongycastle.crypto.digests.SHA1Digest) SHA512Digest(org.spongycastle.crypto.digests.SHA512Digest) SHA224Digest(org.spongycastle.crypto.digests.SHA224Digest) RSAKeyPairGenerator(org.spongycastle.crypto.generators.RSAKeyPairGenerator) SecureRandom(java.security.SecureRandom) RSAKeyGenerationParameters(org.spongycastle.crypto.params.RSAKeyGenerationParameters) OAEPEncoding(org.spongycastle.crypto.encodings.OAEPEncoding) RSAKeyParameters(org.spongycastle.crypto.params.RSAKeyParameters) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) AsymmetricBlockCipher(org.spongycastle.crypto.AsymmetricBlockCipher) Test(org.junit.Test)

Example 5 with AsymmetricCipherKeyPair

use of org.spongycastle.crypto.AsymmetricCipherKeyPair in project rskj by rsksmart.

the class ECIESCoder method encrypt.

public static byte[] encrypt(ECPoint toPub, byte[] plaintext, byte[] macData) {
    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    SecureRandom random = new SecureRandom();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random);
    eGen.init(gParam);
    byte[] iv = new byte[KEY_SIZE / 8];
    new SecureRandom().nextBytes(iv);
    AsymmetricCipherKeyPair ephemPair = eGen.generateKeyPair();
    BigInteger prv = ((ECPrivateKeyParameters) ephemPair.getPrivate()).getD();
    ECPoint pub = ((ECPublicKeyParameters) ephemPair.getPublic()).getQ();
    EthereumIESEngine iesEngine = makeIESEngine(true, toPub, prv, iv);
    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, random);
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);
    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, random));
    byte[] cipher;
    try {
        cipher = iesEngine.processBlock(plaintext, 0, plaintext.length, macData);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write(pub.getEncoded(false));
        bos.write(iv);
        bos.write(cipher);
        return bos.toByteArray();
    } catch (InvalidCipherTextException e) {
        throw Throwables.propagate(e);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
Also used : ECKeyPairGenerator(org.spongycastle.crypto.generators.ECKeyPairGenerator) InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) SecureRandom(java.security.SecureRandom) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ECPoint(org.spongycastle.math.ec.ECPoint) KeyGenerationParameters(org.spongycastle.crypto.KeyGenerationParameters) AsymmetricCipherKeyPair(org.spongycastle.crypto.AsymmetricCipherKeyPair) BigInteger(java.math.BigInteger)

Aggregations

SecureRandom (java.security.SecureRandom)6 AsymmetricCipherKeyPair (org.spongycastle.crypto.AsymmetricCipherKeyPair)6 Test (org.junit.Test)3 KeyGenerationParameters (org.spongycastle.crypto.KeyGenerationParameters)3 SHA256Digest (org.spongycastle.crypto.digests.SHA256Digest)3 ECKeyPairGenerator (org.spongycastle.crypto.generators.ECKeyPairGenerator)3 IOException (java.io.IOException)2 BufferedBlockCipher (org.spongycastle.crypto.BufferedBlockCipher)2 ECDHBasicAgreement (org.spongycastle.crypto.agreement.ECDHBasicAgreement)2 AESFastEngine (org.spongycastle.crypto.engines.AESFastEngine)2 IESEngine (org.spongycastle.crypto.engines.IESEngine)2 KDF2BytesGenerator (org.spongycastle.crypto.generators.KDF2BytesGenerator)2 RSAKeyPairGenerator (org.spongycastle.crypto.generators.RSAKeyPairGenerator)2 HMac (org.spongycastle.crypto.macs.HMac)2 SICBlockCipher (org.spongycastle.crypto.modes.SICBlockCipher)2 RSAKeyGenerationParameters (org.spongycastle.crypto.params.RSAKeyGenerationParameters)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 BigInteger (java.math.BigInteger)1 InvalidKeyException (java.security.InvalidKeyException)1 KeyFactory (java.security.KeyFactory)1