Beispiel #1
0
 public DataStructure createDataStructure() throws DataFormatException {
   PublicKey publicKey = new PublicKey();
   byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
   for (int i = 0; i < data.length; i++) data[i] = (byte) (i % 16);
   publicKey.setData(data);
   return publicKey;
 }
Beispiel #2
0
  public boolean generateKeys() {

    PublicKey keyPub;
    PrivateKey keyPri;
    SecureRandom rand;

    Security.addProvider(new ABAProvider());

    rand = new SecureRandom();

    rand.setSeed(System.currentTimeMillis());

    try {
      KeyPairGenerator fact;
      KeyPair keyPair;

      fact = KeyPairGenerator.getInstance("RSA", "ABA");

      fact.initialize(1024, rand);

      keyPair = fact.generateKeyPair();

      keyPub = keyPair.getPublic();

      keyPri = keyPair.getPrivate();

      pubKey = bytesToHexStr(keyPub.getEncoded());

      priKey = bytesToHexStr(keyPri.getEncoded());
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Beispiel #3
0
  public void testNullEquals() {
    PublicKey publicKey = new PublicKey();
    byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
    for (int i = 0; i < data.length; i++) data[i] = (byte) (i % 56);
    publicKey.setData(data);

    assertFalse(publicKey.equals(null));
  }
Beispiel #4
0
  public void testBase64Constructor() throws Exception {
    PublicKey publicKey = new PublicKey();
    byte data[] = new byte[PublicKey.KEYSIZE_BYTES];
    for (int i = 0; i < data.length; i++) data[i] = (byte) (i % 56);
    publicKey.setData(data);

    PublicKey key2 = new PublicKey(publicKey.toBase64());
    assertEquals(publicKey, key2);
  }
 @Test
 public void testVerification() throws WrongSignatureException {
   String message = "Hello, this is Mycelium";
   String signature =
       "H9MwYMb/ctDd6BcFvtQKUjwq990y3xSm2K6WFZpMx5+7e+G5Ffqm/imFig0VKtiPL1GDryArVJcoEemLAN4+Z9Q=";
   SignedMessage signedMessage = SignedMessage.validate(address, message, signature);
   PublicKey pubkey = signedMessage.getPublicKey();
   Assert.assertEquals(address, pubkey.toAddress(address.getNetwork()));
 }
Beispiel #6
0
 public void testShortRead() throws Exception {
   PublicKey publicKey = new PublicKey();
   ByteArrayInputStream in =
       new ByteArrayInputStream(DataHelper.getASCII("six times nine equals forty-two"));
   boolean error = false;
   try {
     publicKey.readBytes(in);
   } catch (DataFormatException dfe) {
     error = true;
   }
   assertTrue(error);
 }
Beispiel #7
0
  public void testNullData() throws Exception {
    PublicKey publicKey = new PublicKey();
    publicKey.toString();

    boolean error = false;
    try {
      publicKey.writeBytes(new ByteArrayOutputStream());
    } catch (DataFormatException dfe) {
      error = true;
    }
    assertTrue(error);
  }
  public byte[] decryptBytes(byte[] combined) throws IOException, InvalidMessageException {
    try {
      byte[][] parts =
          Util.split(combined, PublicKey.KEY_SIZE, combined.length - PublicKey.KEY_SIZE);
      PublicKey theirPublicKey = new PublicKey(parts[0], 0);

      ECPrivateKey ourPrivateKey = asymmetricMasterSecret.getPrivateKey();
      byte[] secret = Curve.calculateAgreement(theirPublicKey.getKey(), ourPrivateKey);
      MasterCipher masterCipher = getMasterCipherForSecret(secret);

      return masterCipher.decryptBytes(parts[1]);
    } catch (InvalidKeyException e) {
      throw new InvalidMessageException(e);
    }
  }
  public byte[] encryptBytes(byte[] body) {
    try {
      ECPublicKey theirPublic = asymmetricMasterSecret.getDjbPublicKey();
      ECKeyPair ourKeyPair = Curve.generateKeyPair();
      byte[] secret = Curve.calculateAgreement(theirPublic, ourKeyPair.getPrivateKey());
      MasterCipher masterCipher = getMasterCipherForSecret(secret);
      byte[] encryptedBodyBytes = masterCipher.encryptBytes(body);

      PublicKey ourPublicKey = new PublicKey(31337, ourKeyPair.getPublicKey());
      byte[] publicKeyBytes = ourPublicKey.serialize();

      return Util.combine(publicKeyBytes, encryptedBodyBytes);
    } catch (InvalidKeyException e) {
      throw new AssertionError(e);
    }
  }
Beispiel #10
0
  public byte[] createPublicKey() throws CryptoException {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
      keyGen.initialize(DH_SPEC);
      KeyPair keypair = keyGen.generateKeyPair();

      privateKey = keypair.getPrivate();
      PublicKey publicKey = keypair.getPublic();

      return publicKey.getEncoded();
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10001, e);
    } catch (InvalidAlgorithmParameterException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10002, e);
    }
  }
Beispiel #11
0
  public void testShortData() throws Exception {
    PublicKey publicKey = new PublicKey();
    byte data[] = new byte[56];
    for (int i = 0; i < data.length; i++) data[i] = (byte) (i);

    boolean error = false;
    try {
      publicKey.setData(data);
      publicKey.writeBytes(new ByteArrayOutputStream());
    } catch (DataFormatException dfe) {
      error = true;
    } catch (IllegalArgumentException exc) {
      error = true;
    }
    assertTrue(error);
  }
  private static boolean checkKeysEqual(PublicKey pk1, PublicKey pk2) {
    // first, they should have the same format
    // second, their encoded form must be the same

    // assert(pk1 != null);
    // assert(pk2 != null);

    String format1 = pk1.getFormat();
    String format2;
    if ((pk2 == null)
        || (((format2 = pk2.getFormat()) != null) ^ (format1 != null))
        || ((format1 != null) && !format1.equals(format2))) {
      return false;
    }

    return Arrays.equals(pk1.getEncoded(), pk2.getEncoded());
  }
Beispiel #13
0
  @Override
  public KeySelectorResult select(
      final KeyInfo ki, final Purpose p, final AlgorithmMethod m, final XMLCryptoContext c)
      throws KeySelectorException {

    if (ki == null) throw new KeySelectorException("KeyInfo is null");

    final SignatureMethod sm = (SignatureMethod) m;
    @SuppressWarnings("unchecked")
    final List<Object> list = ki.getContent();

    for (final Object l : list) {
      final XMLStructure s = (XMLStructure) l;
      PublicKey pk = null;
      if (s instanceof KeyValue) {
        try {
          pk = ((KeyValue) s).getPublicKey();
        } catch (final KeyException ke) {
          throw new KeySelectorException(ke);
        }

      } else if (s instanceof X509Data) {
        for (final Object d : ((X509Data) s).getContent()) {
          if (d instanceof X509Certificate) {
            pk = ((Certificate) d).getPublicKey();
          }
        }
      }

      if (pk != null) {
        final String sa = sm.getAlgorithm();
        final String ka = pk.getAlgorithm();
        if ("DSA".equalsIgnoreCase(ka) && "http://www.w3.org/2000/09/xmldsig#dsa-sha1".equals(sa)
            || "RSA".equalsIgnoreCase(ka)
                && "http://www.w3.org/2000/09/xmldsig#rsa-sha1".equals(sa)) {
          return new MyKeySelectorResult(pk);
        }
      }
    }

    throw new KeySelectorException("No KeyValue element found");
  }
 // internal implementation of translateKey() for public keys. See JCA doc
 private PublicKey translatePublicKey(PublicKey key) throws InvalidKeyException {
   if (key instanceof RSAPublicKey) {
     if (key instanceof RSAPublicKeyImpl) {
       return key;
     }
     RSAPublicKey rsaKey = (RSAPublicKey) key;
     try {
       return new RSAPublicKeyImpl(rsaKey.getModulus(), rsaKey.getPublicExponent());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPublicKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if ("X.509".equals(key.getFormat())) {
     byte[] encoded = key.getEncoded();
     return new RSAPublicKeyImpl(encoded);
   } else {
     throw new InvalidKeyException(
         "Public keys must be instance " + "of RSAPublicKey or have X.509 encoding");
   }
 }
 public static byte[] func_75895_a(String p_75895_0_, PublicKey p_75895_1_, SecretKey p_75895_2_) {
   try {
     return func_75893_a(
         "SHA-1",
         new byte[][] {
           p_75895_0_.getBytes("ISO_8859_1"), p_75895_2_.getEncoded(), p_75895_1_.getEncoded()
         });
   } catch (UnsupportedEncodingException unsupportedencodingexception) {
     unsupportedencodingexception.printStackTrace();
   }
   return null;
 }
Beispiel #16
0
  /*
   * 产生RSA公私钥对
   */
  public static void genRSAKeyPair() {
    KeyPairGenerator rsaKeyGen = null;
    KeyPair rsaKeyPair = null;
    try {
      System.out.println("Generating a pair of RSA key ... ");
      rsaKeyGen = KeyPairGenerator.getInstance("RSA");
      SecureRandom random = new SecureRandom();
      random.setSeed(System.currentTimeMillis());

      // rsaKeyGen.initialize(1024, random);
      rsaKeyGen.initialize(1024);
      rsaKeyPair = rsaKeyGen.genKeyPair();
      PublicKey rsaPublic = rsaKeyPair.getPublic();
      PrivateKey rsaPrivate = rsaKeyPair.getPrivate();

      System.out.println("公钥:" + bytesToHexStr(rsaPublic.getEncoded()));
      System.out.println("私钥:" + bytesToHexStr(rsaPrivate.getEncoded()));
      System.out.println("1024-bit RSA key GENERATED.");
    } catch (Exception e) {
      System.out.println("genRSAKeyPair:" + e);
    }
  }
Beispiel #17
0
  public static void main(String[] args) {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
      keyGen.initialize(1024, random);

      KeyPair pair = keyGen.generateKeyPair();
      PrivateKey priv = pair.getPrivate();
      PublicKey pub = pair.getPublic();

      byte[] encPriv = priv.getEncoded();
      FileOutputStream privfos = new FileOutputStream("DSAPrivateKey.key");
      privfos.write(encPriv);
      privfos.close();

      byte[] encPub = pub.getEncoded();
      FileOutputStream pubfos = new FileOutputStream("DSAPublicKey.key");
      pubfos.write(encPub);
      pubfos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #18
0
 @Override
 public BitcoinSigner findSignerByPublicKey(PublicKey publicKey) {
   Address address = publicKey.toAddress(_network);
   InMemoryPrivateKey privateKey;
   try {
     privateKey = getPrivateKeyForAddress(address, _cipher);
   } catch (InvalidKeyCipher e) {
     throw new RuntimeException(
         "Unable to decrypt private key for address " + address.toString());
   }
   if (privateKey != null) {
     return privateKey;
   }
   throw new RuntimeException("Unable to find private key for address " + address.toString());
 }
  public boolean connect(String username, String weakSecret, final String server, final int port) {
    System.out.println("attempting to connect");

    try {
      sock = new Socket();
      sock.connect(new InetSocketAddress(server, port));
      output = new ObjectOutputStream(sock.getOutputStream());
      input = new ObjectInputStream(sock.getInputStream());
      output.writeObject(username);

      // do DH exchange and agree on starting message index
      try {
        if (weakSecret != null) // group server connect
        {
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeyWithWeakSecret(username, weakSecret, input, output);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        } else // file server connect
        {
          PublicKey fileServerPublicKey = (PublicKey) input.readObject(); // read in public key

          File savedKeys = new File("savedkeys.bin");
          ArrayList<PublicKey> knownKeys = new ArrayList<PublicKey>();
          if (savedKeys.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(savedKeys));
            knownKeys = (ArrayList<PublicKey>) in.readObject();
          }
          if (!knownKeys.contains(fileServerPublicKey)) // prompt the user to verify the key
          {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] digest = sha.digest(fileServerPublicKey.getEncoded());
            System.out.println("RSA key fingerprint is " + getFingerprint(digest));
            System.out.println(
                "Please verify this is correct by contacting the file server owner.");
            System.out.println(
                "Do you want to add this key to your list of saved servers? (yes/no)");
            Scanner scanner = new Scanner(System.in);
            String answer = scanner.nextLine();
            if (answer.toLowerCase().equals("yes")) {
              knownKeys.add(fileServerPublicKey);
              savedKeys.delete();
              savedKeys.createNewFile();
              ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(savedKeys));
              out.writeObject(knownKeys);
              out.flush();
              out.close();
              output.writeObject("yes");
            } else {
              output.writeObject("no");
              System.out.println("Exiting");
              System.exit(0);
            }
          } else // accpet the key without prompt
          output.writeObject("yes");

          generateRSAKeypair();
          output.writeObject(publicKey);
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeySignedExchange(
                  input, output, privateKey, fileServerPublicKey);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        }

        encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] key = sha.digest(encryptionKey.getEncoded());
        key = Arrays.copyOf(key, 16); // use only first 128 bit

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));

        BigInteger R = new BigInteger(128, new SecureRandom());
        output.writeObject(encryptCipher.doFinal(R.toByteArray()));
        BigInteger start = new BigInteger(decryptCipher.doFinal((byte[]) input.readObject()));
        if (start.compareTo(R) < 0) throw new Exception("Invalid message index from server");
        else messageIndex = start.add(BigInteger.ONE);
      } catch (Exception ex) {
        System.out.println("Failed to connect: " + ex.getMessage());
        // if anything fails, we are not connected
        sock = null;
        return false;
      }
    } catch (IOException ex) {
      return false;
    }

    return true;
  }
Beispiel #20
0
 public static BigInteger encrypt(PublicKey k, BigInteger m) {
   return m.modPow(k.getE(), k.getN());
 }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }