/**
   * Created primary key using openssl.
   *
   * <p>openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj
   * '/C=GB/ST=/L=Manchester/CN=www.example.com' -keyout myrsakey.pem -out /tmp/myrsacert.pem
   * openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
   */
  private static PrivateKey getPrivateKey() {
    String str =
        "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n"
            + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n"
            + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n"
            + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n"
            + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n"
            + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n"
            + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n"
            + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n"
            + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n"
            + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n"
            + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n"
            + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n"
            + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n"
            + "UHgqXmuvk2X/Ww==";

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      PKCS8EncodedKeySpec privKeySpec =
          new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
      return fac.generatePrivate(privKeySpec);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #2
0
  public SymmetricCryptor getSymmetricCryptor(
      byte[] peerPublicKeyBytes, boolean useSealedObject, ClassLoader classLoader)
      throws CryptoException {
    if (privateKey == null) {
      throw new IllegalStateException(
          "KeyGenerator did not successfully generate public key"); //$NON-NLS-1$
    }
    try {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(peerPublicKeyBytes);
      KeyFactory keyFact = KeyFactory.getInstance(ALGORITHM);
      PublicKey publicKey = keyFact.generatePublic(x509KeySpec);

      KeyAgreement ka = KeyAgreement.getInstance(ALGORITHM);
      ka.init(privateKey);
      ka.doPhase(publicKey, true);
      byte[] secret = ka.generateSecret();

      MessageDigest sha = MessageDigest.getInstance(DIGEST);
      byte[] hash = sha.digest(secret);
      byte[] symKey = new byte[keySize / 8];
      System.arraycopy(hash, 0, symKey, 0, symKey.length);
      SymmetricCryptor sc = SymmetricCryptor.getSymmectricCryptor(symKey);
      sc.setUseSealedObject(useSealedObject);
      sc.setClassLoader(classLoader);
      return sc;
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10003, e);
    } catch (InvalidKeySpecException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10004, e);
    } catch (InvalidKeyException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10005, e);
    }
  }
  public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] localObject = null;

    if (paramE_CODE == E_CODE.RSA) {
      if (rsa_key.length() > 2) {
        Cipher localCipher;
        byte[] arrayOfByte = new byte[0];
        //		    PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new
        // X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
        PublicKey localPublicKey =
            KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT)));
        System.out.println("key  length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length);
        System.out.println("data length-" + paramArrayOfByte.length);
        localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher.init(Cipher.DECRYPT_MODE, localPublicKey);
        //		    localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);

        arrayOfByte = localCipher.doFinal(paramArrayOfByte);
        //		    int oldLength;
        //		    for (int i = 0; i < paramArrayOfByte.length; i += 8) {
        //		        byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8);
        //		        oldLength = arrayOfByte.length;
        //		        arrayOfByte  = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length);
        //		        System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length);
        //		    }

        //		    arrayOfByte = paramArrayOfByte;

        return arrayOfByte;
      }
    } else if (paramE_CODE == E_CODE.RSA_EP) {
      if (rsa_ep_key.length() >= 2) {
        //        PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new
        // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key)));
        PrivateKey localPrivateKey =
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT)));
        Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher2.init(2, localPrivateKey);
        localObject = localCipher2.doFinal(paramArrayOfByte);
      }
    } else if (paramE_CODE == E_CODE.AES) {
      //      SecretKeySpec localSecretKeySpec = new
      // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      SecretKeySpec localSecretKeySpec =
          new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);
      Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
      localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1);
      localObject = arrayOfByte2;
    }

    return localObject;
  }
 /**
  * Converts a PEM-encoded PKCS#8 private key into an RSAPrivateKey instance useable with JCE
  *
  * @param privateKey private key in PKCS#8 format and PEM-encoded
  * @return RSAPrivateKey instance containing the key
  */
 private static RSAPrivateKey rsaPrivateKeyDecode(final String privateKey) {
   try {
     final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
     final KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodePadded(privateKey));
     return (RSAPrivateKey) keyFactory.generatePrivate(ks);
   } catch (final Exception e) {
     throw new RuntimeException("Failed to decode built-in private key", e);
   }
 }
Example #5
0
  /**
   * ��ȡWEB������·��
   *
   * @return
   */
  public static String getWebinfPath() {
    String strWebPath = "";

    String res = null;

    KeyFactory oTemp = new KeyFactory();
    String classname = oTemp.getClass().getName().replace('.', File.separatorChar) + ".class";

    ClassLoader oClassLoader = oTemp.getClass().getClassLoader();

    if (oClassLoader != null) {
      java.net.URL url = oClassLoader.getResource(classname);

      if (url != null) {
        String filePath = url.getFile();
        int fileStrPosition = filePath.indexOf("file:/");
        int begin = 0;
        int end = filePath.length();

        if (fileStrPosition >= 0) {
          begin = fileStrPosition + "file:".length();
        }

        // ���ж��Ƿ���δ����ļ�
        end = filePath.indexOf("classes/" + classname);
        if (end < 0) {
          // �������webModule�����jar��
          end = filePath.indexOf("lib/");
          if (end < 0) {
            // ����ͨĿ¼�µ�jar��
            int tmpend = filePath.indexOf("!/");

            if (tmpend >= 0) {
              end = filePath.substring(0, tmpend).lastIndexOf("/");
            }
          }
        }

        String rf = "";
        if (end < 0) {
          rf = filePath.substring(begin, filePath.length());
        } else {
          rf = filePath.substring(begin, end);
        }

        res = new File(rf).getAbsolutePath().replace('\\', '/') + "/";
      }
    }
    try {
      strWebPath = java.net.URLDecoder.decode(res, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
    }

    return strWebPath;
  }
 private PrivateKey getPrivateKey(BigInteger privExp, BigInteger modulus)
     throws InvalidKeySpecException {
   RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modulus, privExp);
   KeyFactory keyFactory = null;
   try {
     keyFactory = KeyFactory.getInstance("RSA");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   return keyFactory.generatePrivate(privSpec);
 }
Example #7
0
 /**
  * used to reconstitute public key sent in byte form from peer
  *
  * @param encodedKey
  * @return PublicKey
  */
 private PublicKey generatePubKey(byte[] encodedKey) {
   PublicKey pubKey = null;
   try {
     KeyFactory KeyFac = KeyFactory.getInstance(getAlgorithm(asymAlgorithm));
     X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
     pubKey = KeyFac.generatePublic(x509KeySpec);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return pubKey;
 }
 /**
  * Complete the key agreement protocol with the peer public value <code>otherPublic</code> and
  * return the calculated shared secret.
  *
  * @param otherPublic The peer public value.
  * @return The shared secret value produced by the protocol.
  */
 public byte[] getSharedSecret(BigInteger otherPublic) {
   try {
     KeyFactory factory = KeyFactory.getInstance("DH");
     DHPublicKeySpec pub = new DHPublicKeySpec(otherPublic, P1024, G);
     PublicKey key = factory.generatePublic(pub);
     dh.doPhase(key, true);
     return dh.generateSecret();
   } catch (GeneralSecurityException e) {
     throw new TorException(e);
   }
 }
  public static VotifierKeyPair read(JsonObject source) throws Exception {
    byte[] publicKeyEnc = Base64.getDecoder().decode(source.get("public_key").getAsString());
    byte[] privateKeyEnc = Base64.getDecoder().decode(source.get("private_key").getAsString());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyEnc));
    PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyEnc));

    return new VotifierKeyPair(new KeyPair(publicKey, privateKey));
  }
 public static void savePublicKeyInFile(String path, PublicKey key) {
   try {
     KeyFactory fac = KeyFactory.getInstance("RSA");
     RSAPublicKeySpec RSAspec = fac.getKeySpec(key, RSAPublicKeySpec.class);
     FileOutputStream file3 = new FileOutputStream(path);
     ObjectOutputStream obj_stream = new ObjectOutputStream(file3);
     obj_stream.writeObject(RSAspec.getModulus());
     obj_stream.writeObject(RSAspec.getPublicExponent());
   } catch (Exception ex) {
     System.err.println("Probeleme de sauvegarde de la cle public dans un fichier: " + ex);
   }
 }
 public static PublicKey func_75896_a(byte p_75896_0_[]) {
   try {
     X509EncodedKeySpec x509encodedkeyspec = new X509EncodedKeySpec(p_75896_0_);
     KeyFactory keyfactory = KeyFactory.getInstance("RSA");
     return keyfactory.generatePublic(x509encodedkeyspec);
   } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
     nosuchalgorithmexception.printStackTrace();
   } catch (InvalidKeySpecException invalidkeyspecexception) {
     invalidkeyspecexception.printStackTrace();
   }
   System.err.println("Public key reconstitute failed!");
   return null;
 }
Example #12
0
 /**
  * Get the secret data that has been agreed on through Diffie-Hellman key agreement protocol. Note
  * that in the two party protocol, if the peer keys are already known, no other data needs to be
  * sent in order to agree on a secret. That is, a secured message may be sent without any
  * mandatory round-trip overheads.
  *
  * <p>It is illegal to call this member function if the private key has not been set (or
  * generated).
  *
  * @param peerPublicKey the peer's public key.
  * @returns the secret, which is an unsigned big-endian integer the same size as the
  *     Diffie-Hellman modulus.
  */
 SecretKey getAgreedSecret(BigInteger peerPublicValue) {
   try {
     KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
     DHPublicKeySpec spec = new DHPublicKeySpec(peerPublicValue, modulus, base);
     PublicKey publicKey = kf.generatePublic(spec);
     KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");
     ka.init(privateKey);
     ka.doPhase(publicKey, true);
     return ka.generateSecret("TlsPremasterSecret");
   } catch (GeneralSecurityException e) {
     throw new RuntimeException("Could not generate secret", e);
   }
 }
Example #13
0
 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("DH");
     return (DHPublicKeySpec) factory.getKeySpec(key, DHPublicKeySpec.class);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #14
0
  public PublicKey LoadPublicKey(String path, String algorithm)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "public.key");
    FileInputStream fis = new FileInputStream(path + "public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Generate PublicKey.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    return publicKey;
  }
  /**
   * Convert a byte array to an EC private key by decoding the D number parameter.
   *
   * @param keyBytes Bytes to be converted to the EC private key.
   * @return An instance of EC private key decoded from the input bytes.
   * @throws InvalidKeySpecException The provided key bytes are not a valid EC private key.
   */
  @Override
  public PrivateKey convertBytesToPrivateKey(byte[] keyBytes) throws InvalidKeySpecException {
    try {
      KeyFactory kf = KeyFactory.getInstance("ECDH", getProviderName());
      BigInteger keyInteger = new BigInteger(keyBytes);
      ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
      ECPrivateKeySpec pubSpec = new ECPrivateKeySpec(keyInteger, ecSpec);

      ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(pubSpec);
      return privateKey;
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }
Example #16
0
 /**
  * Generates a PublicKey instance from a string containing the Base64-encoded public key.
  *
  * @param encodedPublicKey Base64-encoded public key
  * @throws IllegalArgumentException if encodedPublicKey is invalid
  */
 private PublicKey generatePublicKey(String encodedPublicKey) {
   try {
     byte[] decodedKey = Base64.decode(encodedPublicKey);
     KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
     return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   } catch (InvalidKeySpecException e) {
     Log.e(TAG, "Invalid key specification.");
     throw new IllegalArgumentException(e);
   } catch (Base64DecoderException e) {
     Log.e(TAG, "Base64 decoding failed.");
     throw new IllegalArgumentException(e);
   }
 }
Example #17
0
 @Override
 public Key next() {
   if (!hasNext()) {
     throw new NoSuchElementException();
   }
   return KeyFactory.createKey(parent, kind, next++, appIdNamespace);
 }
 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response putTaskData(String value) {
   Response res = null;
   // add your code here
   // first check if the Entity exists in the datastore
   DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
   MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
   syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
   Key entKey = KeyFactory.createKey("TaskData", keyname);
   Date date = new Date();
   try {
     // if it is, signal that we updated the entity
     Entity ts = datastore.get(entKey);
     ts.setProperty("value", value);
     ts.setProperty("date", date);
     datastore.put(ts);
     res = Response.noContent().build();
   } catch (EntityNotFoundException e) {
     // if it is not, create it and
     // signal that we created the entity in the datastore
     Entity taskdata = new Entity("TaskData", keyname);
     taskdata.setProperty("value", value);
     taskdata.setProperty("date", date);
     datastore.put(taskdata);
     res = Response.created(uriInfo.getAbsolutePath()).build();
   }
   TaskData td = new TaskData(keyname, value, date);
   syncCache.put(keyname, td);
   return res;
 }
Example #19
0
 public void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception {
   DSAPublicKeySpec dsaPubKeySpec =
       new DSAPublicKeySpec(
           new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g));
   PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);
   signature.initVerify(pubKey);
 }
Example #20
0
 public void setPrvKey(byte[] x, byte[] p, byte[] q, byte[] g) throws Exception {
   DSAPrivateKeySpec dsaPrivKeySpec =
       new DSAPrivateKeySpec(
           new BigInteger(x), new BigInteger(p), new BigInteger(q), new BigInteger(g));
   PrivateKey prvKey = keyFactory.generatePrivate(dsaPrivKeySpec);
   signature.initSign(prvKey);
 }
Example #21
0
 /**
  * Construct a private key from its encoding.
  *
  * @param encodedKey the encoding of a private key.
  * @param encodedKeyAlgorithm the algorithm the wrapped key is for.
  * @return a private key constructed from the encodedKey.
  */
 private static final PrivateKey constructPrivateKey(byte[] encodedKey, String encodedKeyAlgorithm)
     throws InvalidKeyException, NoSuchAlgorithmException {
   try {
     KeyFactory keyFactory = KeyFactory.getInstance(encodedKeyAlgorithm);
     PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
     return keyFactory.generatePrivate(keySpec);
   } catch (NoSuchAlgorithmException nsae) {
     throw new NoSuchAlgorithmException(
         "No installed providers "
             + "can create keys for the "
             + encodedKeyAlgorithm
             + "algorithm",
         nsae);
   } catch (InvalidKeySpecException ike) {
     throw new InvalidKeyException("Cannot construct private key", ike);
   }
 }
 protected Key getMetadataKeyForBlobKey(BlobKey blobKey) {
   String origNamespace = NamespaceManager.get();
   NamespaceManager.set("");
   try {
     return KeyFactory.createKey(null, BlobInfoFactory.KIND, blobKey.getKeyString());
   } finally {
     NamespaceManager.set(origNamespace);
   }
 }
Example #23
0
  private boolean checkSignature(String publicKey, String strToSign, byte[] sign) {
    try {
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      byte[] encodedKey = Base64.decodeBase64(publicKey);
      PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
      java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
      signature.initVerify(pubKey);
      signature.update(strToSign.getBytes());
      return signature.verify(sign);

    } catch (InvalidKeySpecException
        | NoSuchAlgorithmException
        | SignatureException
        | InvalidKeyException e) {
      log.error(e.getMessage());
    }
    return false;
  }
Example #24
0
  public static Entity GetEntity(String slideKey, String questionText, int rating) {

    Entity questionEntity = new Entity("Question", KeyFactory.stringToKey(slideKey));
    questionEntity.setProperty("Text", questionText);
    questionEntity.setProperty("Rating", rating);
    questionEntity.setProperty("DatePosted", new Date());

    return questionEntity;
  }
Example #25
0
  public static Question GetQuestion(Entity entity) {
    Question q = new Question();
    q.key = KeyFactory.keyToString(entity.getKey());
    q.questionText = (String) entity.getProperty("Text");
    q.rating = (Long) entity.getProperty("Rating");
    q.datePosted = (Date) entity.getProperty("DatePosted");

    return q;
  }
  /**
   * Converts byte array to an EC public key, by decoding the Q point parameter.
   *
   * @param keyBytes Bytes to be converted to EC public key.
   * @return An instance of the EC public key on success, or null on failure.
   * @throws InvalidKeySpecException When provided bytes are not a correct key representation.
   */
  @Override
  public PublicKey convertBytesToPublicKey(byte[] keyBytes) throws InvalidKeySpecException {
    try {
      KeyFactory kf = KeyFactory.getInstance("ECDH", getProviderName());

      ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
      if (ecSpec == null) { // can happen with incorrectly initialized crypto provider
        return null;
      }
      ECPoint point = ecSpec.getCurve().decodePoint(keyBytes);
      ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

      ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(pubSpec);
      return publicKey;
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }
Example #27
0
  public byte[] getK() throws Exception {
    if (K == null) {
      KeyFactory myKeyFac = KeyFactory.getInstance("DH");
      DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g);
      PublicKey yourPubKey = myKeyFac.generatePublic(keySpec);

      myKeyAgree.doPhase(yourPubKey, true);
      byte[] mySharedSecret = myKeyAgree.generateSecret();

      K = new BigInteger(mySharedSecret);
      K_array = K.toByteArray();

      // System.err.println("K.signum(): "+K.signum()+
      // " "+Integer.toHexString(mySharedSecret[0]&0xff)+
      // " "+Integer.toHexString(K_array[0]&0xff));

      K_array = mySharedSecret;
    }
    return K_array;
  }
 static {
   try {
     FileInputStream keyfis = new FileInputStream("src/com/ingenium/ash/publicIngenium");
     byte[] encKey = new byte[keyfis.available()];
     keyfis.read(encKey);
     keyfis.close();
     X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
     KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
     pubKey = keyFactory.generatePublic(pubKeySpec);
   } catch (InvalidKeySpecException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchAlgorithmException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchProviderException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (FileNotFoundException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Example #29
0
  public String toString() {
    StringBuilder b = new StringBuilder();
    Key k = KeyFactory.stringToKey(key);
    b.append("Question (").append(k.getId()).append(") : ").append(" Text=").append(questionText);
    b.append(" Date Posted=").append(datePosted);
    b.append(" ParentInfo = ").append(k.getParent().toString());
    b.append("\n");

    for (Comment c : comments) {
      b.append("\t\t").append(c.toString()).append("\n");
    }

    return b.toString();
  }
Example #30
0
  KeyRange(Key parent, String kind, long start, long end, AppIdNamespace appIdNamespace) {
    if (parent != null && !parent.isComplete()) {
      throw new IllegalArgumentException("Invalid parent: not a complete key");
    }

    if (kind == null || kind.equals("")) {
      throw new IllegalArgumentException("Invalid kind: cannot be null or empty");
    }

    if (start < 1) {
      throw new IllegalArgumentException("Illegal start " + start + ": less than 1");
    }

    if (end < start) {
      throw new IllegalArgumentException("Illegal end " + end + ": less than start " + start);
    }

    this.parent = parent;
    this.kind = kind;
    this.appIdNamespace = appIdNamespace;
    this.start = KeyFactory.createKey(parent, kind, start, appIdNamespace);
    this.end = KeyFactory.createKey(parent, kind, end, appIdNamespace);
  }