예제 #1
0
  public static void main(String[] args) {
    try {

      AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DSA");
      paramGen.init(1024);

      AlgorithmParameters params = paramGen.generateParameters();

      DSAParameterSpec dsaParameterSpec = params.getParameterSpec(DSAParameterSpec.class);

      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
      keyPairGenerator.initialize(dsaParameterSpec);

      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      PublicKey publicKey = keyPair.getPublic();
      PrivateKey privateKey = keyPair.getPrivate();

      saveKey("BpubKey", publicKey);
      saveKey("BprivKey", privateKey);

    } catch (NoSuchAlgorithmException
        | InvalidParameterSpecException
        | InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }
  }
  /**
   * Generates and returns {@link DHParameterSpec}.
   *
   * @return {@link String}
   * @see AlgorithmParameters
   * @see AlgorithmParameterGenerator
   */
  public static DHParameterSpec generateDiffieHellmanValues()
      throws NoSuchAlgorithmException, InvalidParameterSpecException {

    AlgorithmParameterGenerator parameterGenerator = AlgorithmParameterGenerator.getInstance("DH");
    parameterGenerator.init(1024);

    AlgorithmParameters parameters = parameterGenerator.generateParameters();
    return (DHParameterSpec) parameters.getParameterSpec(DHParameterSpec.class);
  }
예제 #3
0
  /** Can be used to generate new parameters */
  public static void main(String[] args) throws Exception {
    AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance(ALGORITHM);
    paramGen.init(1024);

    AlgorithmParameters params = paramGen.generateParameters();

    DHParameterSpec dhSpec = params.getParameterSpec(DHParameterSpec.class);
    System.out.println("l=" + dhSpec.getL());
    System.out.println("g=" + dhSpec.getG());
    System.out.println("p=" + dhSpec.getP());
  }
예제 #4
0
  private void testParameters() throws Exception {
    AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
    a.init(512, random);
    AlgorithmParameters params = a.generateParameters();

    byte[] encodeParams = params.getEncoded();

    AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
    a2.init(encodeParams);

    // a and a2 should be equivalent!
    byte[] encodeParams_2 = a2.getEncoded();

    if (!areEqual(encodeParams, encodeParams_2)) {
      fail("encode/decode parameters failed");
    }

    DSAParameterSpec dsaP = (DSAParameterSpec) params.getParameterSpec(DSAParameterSpec.class);

    KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC");
    g.initialize(dsaP, new SecureRandom());
    KeyPair p = g.generateKeyPair();

    PrivateKey sKey = p.getPrivate();
    PublicKey vKey = p.getPublic();

    Signature s = Signature.getInstance("DSA", "BC");
    byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    s.initSign(sKey);

    s.update(data);

    byte[] sigBytes = s.sign();

    s = Signature.getInstance("DSA", "BC");

    s.initVerify(vKey);

    s.update(data);

    if (!s.verify(sigBytes)) {
      fail("DSA verification failed");
    }
  }
예제 #5
0
  /**
   * Gets the public information for a DH key exchange or null if the parameters could not be made
   *
   * @return a PubInfo object that holds the public information for a DH key exchange or null if the
   *     parameters could not be made
   */
  public static PubInfo getPubParams() {
    try {
      AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
      paramGen.init(1024);
      AlgorithmParameters params = paramGen.generateParameters();

      DHParameterSpec dhSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);

      BigInteger g = dhSpec.getG();
      BigInteger p = dhSpec.getP();
      int l = dhSpec.getL();

      return new PubInfo(g, p, l);
    } catch (Exception e) {
      if (DEBUG) {
        System.out.println("Could not make public parameters");
      }
      return null;
    }
  }
예제 #6
0
  public static void main(String[] args) {
    tcount = 0;
    try {
      ServerSocket ss = new ServerSocket(4567);

      AlgorithmParameterGenerator gerador = AlgorithmParameterGenerator.getInstance("DH");
      gerador.init(1024);
      AlgorithmParameters parametros = gerador.generateParameters();
      DHParameterSpec dhSpec = (DHParameterSpec) parametros.getParameterSpec(DHParameterSpec.class);

      while (true) {
        Socket s = ss.accept();
        tcount++;
        TServidor ts = new TServidor(s, tcount, dhSpec);
        ts.start();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #7
0
  private void testRandom(int size) throws Exception {
    AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("ElGamal", "BC");
    a.init(size, new SecureRandom());
    AlgorithmParameters params = a.generateParameters();

    byte[] encodeParams = params.getEncoded();

    AlgorithmParameters a2 = AlgorithmParameters.getInstance("ElGamal", "BC");
    a2.init(encodeParams);

    // a and a2 should be equivalent!
    byte[] encodeParams_2 = a2.getEncoded();

    if (!areEqual(encodeParams, encodeParams_2)) {
      fail(this.getName() + ": encode/decode parameters failed");
    }

    DHParameterSpec elP = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);

    testGP(size, 0, elP.getG(), elP.getP());
  }
  AlgorithmParameters generateParameters(
      ASN1ObjectIdentifier encryptionOID, SecretKey encKey, SecureRandom rand) throws CMSException {
    try {
      AlgorithmParameterGenerator pGen = createAlgorithmParameterGenerator(encryptionOID);

      if (encryptionOID.equals(CMSAlgorithm.RC2_CBC)) {
        byte[] iv = new byte[8];

        rand.nextBytes(iv);

        try {
          pGen.init(new RC2ParameterSpec(encKey.getEncoded().length * 8, iv), rand);
        } catch (InvalidAlgorithmParameterException e) {
          throw new CMSException("parameters generation error: " + e, e);
        }
      }

      return pGen.generateParameters();
    } catch (NoSuchAlgorithmException e) {
      return null;
    } catch (GeneralSecurityException e) {
      throw new CMSException("exception creating algorithm parameter generator: " + e, e);
    }
  }
  private void run(String mode) throws Exception {

    DHParameterSpec dhSkipParamSpec;

    if (mode.equals("GENERATE_DH_PARAMS")) {
      // Some central authority creates new DH parameters
      System.out.println("Creating Diffie-Hellman parameters (takes VERY long) ...");
      AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
      paramGen.init(512);
      AlgorithmParameters params = paramGen.generateParameters();
      dhSkipParamSpec = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
    } else {
      // use some pre-generated, default DH parameters
      System.out.println("Using SKIP Diffie-Hellman parameters");
      dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
    }

    /*
     * Alice creates her own DH key pair, using the DH parameters from
     * above
     */
    System.out.println("ALICE: Generate DH keypair ...");
    KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
    aliceKpairGen.initialize(dhSkipParamSpec);
    KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

    // Alice creates and initializes her DH KeyAgreement object
    System.out.println("ALICE: Initialization ...");
    KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
    aliceKeyAgree.init(aliceKpair.getPrivate());

    // Alice encodes her public key, and sends it over to Bob.
    byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();

    /*
     * Let's turn over to Bob. Bob has received Alice's public key
     * in encoded format.
     * He instantiates a DH public key from the encoded key material.
     */
    KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(alicePubKeyEnc);
    PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);

    /*
     * Bob gets the DH parameters associated with Alice's public key.
     * He must use the same parameters when he generates his own key
     * pair.
     */
    DHParameterSpec dhParamSpec = ((DHPublicKey) alicePubKey).getParams();

    // Bob creates his own DH key pair
    System.out.println("BOB: Generate DH keypair ...");
    KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
    bobKpairGen.initialize(dhParamSpec);
    KeyPair bobKpair = bobKpairGen.generateKeyPair();

    // Bob creates and initializes his DH KeyAgreement object
    System.out.println("BOB: Initialization ...");
    KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
    bobKeyAgree.init(bobKpair.getPrivate());

    // Bob encodes his public key, and sends it over to Alice.
    byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();

    /*
     * Alice uses Bob's public key for the first (and only) phase
     * of her version of the DH
     * protocol.
     * Before she can do so, she has to instantiate a DH public key
     * from Bob's encoded key material.
     */
    KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
    x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
    PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
    System.out.println("ALICE: Execute PHASE1 ...");
    aliceKeyAgree.doPhase(bobPubKey, true);

    /*
     * Bob uses Alice's public key for the first (and only) phase
     * of his version of the DH
     * protocol.
     */
    System.out.println("BOB: Execute PHASE1 ...");
    bobKeyAgree.doPhase(alicePubKey, true);

    /*
     * At this stage, both Alice and Bob have completed the DH key
     * agreement protocol.
     * Both generate the (same) shared secret.
     */
    byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
    int aliceLen = aliceSharedSecret.length;

    byte[] bobSharedSecret = new byte[aliceLen];
    int bobLen;
    try {
      // show example of what happens if you
      // provide an output buffer that is too short
      bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
    } catch (ShortBufferException e) {
      System.out.println(e.getMessage());
    }
    // provide output buffer of required size
    bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);

    System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
    System.out.println("Bob secret: " + toHexString(bobSharedSecret));

    if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
      throw new Exception("Shared secrets differ");
    System.out.println("Shared secrets are the same");

    /*
     * Now let's return the shared secret as a SecretKey object
     * and use it for encryption. First, we generate SecretKeys for the
     * "DES" algorithm (based on the raw shared secret data) and
     * then we use DES in ECB mode
     * as the encryption algorithm. DES in ECB mode does not require any
     * parameters.
     *
     * Then we use DES in CBC mode, which requires an initialization
     * vector (IV) parameter. In CBC mode, you need to initialize the
     * Cipher object with an IV, which can be supplied using the
     * javax.crypto.spec.IvParameterSpec class. Note that you have to use
     * the same IV for encryption and decryption: If you use a different
     * IV for decryption than you used for encryption, decryption will
     * fail.
     *
     * NOTE: If you do not specify an IV when you initialize the
     * Cipher object for encryption, the underlying implementation
     * will generate a random one, which you have to retrieve using the
     * javax.crypto.Cipher.getParameters() method, which returns an
     * instance of java.security.AlgorithmParameters. You need to transfer
     * the contents of that object (e.g., in encoded format, obtained via
     * the AlgorithmParameters.getEncoded() method) to the party who will
     * do the decryption. When initializing the Cipher for decryption,
     * the (reinstantiated) AlgorithmParameters object must be passed to
     * the Cipher.init() method.
     */
    System.out.println("Return shared secret as SecretKey object ...");
    // Bob
    // NOTE: The call to bobKeyAgree.generateSecret above reset the key
    // agreement object, so we call doPhase again prior to another
    // generateSecret call
    bobKeyAgree.doPhase(alicePubKey, true);
    SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");

    // Alice
    // NOTE: The call to aliceKeyAgree.generateSecret above reset the key
    // agreement object, so we call doPhase again prior to another
    // generateSecret call
    aliceKeyAgree.doPhase(bobPubKey, true);
    SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");

    /*
     * Bob encrypts, using DES in ECB mode
     */
    Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

    byte[] cleartext = "This is just an example".getBytes();
    byte[] ciphertext = bobCipher.doFinal(cleartext);

    /*
     * Alice decrypts, using DES in ECB mode
     */
    Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
    byte[] recovered = aliceCipher.doFinal(ciphertext);

    if (!java.util.Arrays.equals(cleartext, recovered))
      throw new Exception("DES in CBC mode recovered text is " + "different from cleartext");
    System.out.println("DES in ECB mode recovered text is " + "same as cleartext");

    /*
     * Bob encrypts, using DES in CBC mode
     */
    bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

    cleartext = "This is just an example".getBytes();
    ciphertext = bobCipher.doFinal(cleartext);
    // Retrieve the parameter that was used, and transfer it to Alice in
    // encoded format
    byte[] encodedParams = bobCipher.getParameters().getEncoded();

    /*
     * Alice decrypts, using DES in CBC mode
     */
    // Instantiate AlgorithmParameters object from parameter encoding
    // obtained from Bob
    AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
    params.init(encodedParams);
    aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
    recovered = aliceCipher.doFinal(ciphertext);

    if (!java.util.Arrays.equals(cleartext, recovered))
      throw new Exception("DES in CBC mode recovered text is " + "different from cleartext");
    System.out.println("DES in CBC mode recovered text is " + "same as cleartext");
  }