/** * 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; }
public void testMethodKey() throws Exception { MethodKey factory = (MethodKey) KeyFactory.create(MethodKey.class); Set methodSet = new HashSet(); methodSet.add(factory.newInstance(Number.class, new Class[] {int.class})); assertTrue(methodSet.contains(factory.newInstance(Number.class, new Class[] {int.class}))); assertTrue(!methodSet.contains(factory.newInstance(Number.class, new Class[] {Integer.class}))); }
@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; }
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; }
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; }
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(); }
public void main(Provider p) throws Exception { /* * Use Solaris SPARC 11.2 or later to avoid an intermittent failure * when running SunPKCS11-Solaris (8044554) */ if (p.getName().equals("SunPKCS11-Solaris") && System.getProperty("os.name").equals("SunOS") && System.getProperty("os.arch").equals("sparcv9") && System.getProperty("os.version").compareTo("5.11") <= 0 && getDistro().compareTo("11.2") < 0) { System.out.println( "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping"); return; } long start = System.currentTimeMillis(); provider = p; data = new byte[2048]; new Random().nextBytes(data); KeyStore ks = getKeyStore(); KeyFactory kf = KeyFactory.getInstance("RSA", provider); for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); if (ks.isKeyEntry(alias)) { System.out.println("* Key " + alias + "..."); PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password); PublicKey publicKey = ks.getCertificate(alias).getPublicKey(); privateKey = (PrivateKey) kf.translateKey(privateKey); publicKey = (PublicKey) kf.translateKey(publicKey); test(privateKey, publicKey); } } long stop = System.currentTimeMillis(); System.out.println("All tests passed (" + (stop - start) + " ms)."); }
@DELETE public void deleteIt() { // delete an entity from the datastore // just print a message upon exception (don't throw) DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); if (syncCache.get(keyname) != null) { syncCache.delete(keyname); } Key entKey = KeyFactory.createKey("TaskData", keyname); try { Entity ent = datastore.get(entKey); datastore.delete(entKey); System.err.println("TaskData deleted in Datastore"); } catch (EntityNotFoundException e) { System.err.println("TaskData not found in Datastore"); } }
// for the application @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public TaskData getTaskData() { // same code as above method DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); if (syncCache.get(keyname) != null) { TaskData ts = (TaskData) syncCache.get(keyname); return ts; } Key entKey = KeyFactory.createKey("TaskData", keyname); try { Entity ent = datastore.get(entKey); TaskData ts = new TaskData(keyname, (String) ent.getProperty("value"), (Date) ent.getProperty("date")); return ts; } catch (EntityNotFoundException e) { throw new RuntimeException("Get: TaskData with " + keyname + " not found"); } }
// for the browser @GET @Produces(MediaType.TEXT_XML) public TaskData getTaskDataHTML() { // add your code here (get Entity from datastore using this.keyname) // throw new RuntimeException("Get: TaskData with " + keyname + " not found"); // if not found DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); if (syncCache.get(keyname) != null) { TaskData ts = (TaskData) syncCache.get(keyname); return ts; } Key entKey = KeyFactory.createKey("TaskData", keyname); try { Entity ent = datastore.get(entKey); TaskData ts = new TaskData(keyname, (String) ent.getProperty("value"), (Date) ent.getProperty("date")); return ts; } catch (EntityNotFoundException e) { throw new RuntimeException("Get: TaskData with " + keyname + " not found"); } }
public void testEqualOtherClass() throws Exception { MyKey mykey = (MyKey) KeyFactory.create(MyKey.class); assertTrue(!mykey.newInstance(5, new int[] {6, 7}, false).equals(new Object())); }
public void testBooleanArray() throws Exception { BooleanArrayKey f = (BooleanArrayKey) KeyFactory.create(BooleanArrayKey.class); Object key1 = f.newInstance(new boolean[] {true, false, true}); Object key2 = f.newInstance(new boolean[] {true, false, true}); assertTrue(key1.equals(key2)); }
public void testCharArray() throws Exception { CharArrayKey f = (CharArrayKey) KeyFactory.create(CharArrayKey.class); Object key1 = f.newInstance(new char[] {'a', 'b'}); Object key2 = f.newInstance(new char[] {'a', '_'}); assertTrue(!key1.equals(key2)); }
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.getWriter().println("<html><body>"); String keyname = req.getParameter("keyname"); String value = req.getParameter("value"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); // Using the synchronous cache. MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); // display every element of kind TaskData for /datastore if (req.getParameterMap().isEmpty()) { // querying from datastore resp.getWriter().println("<h3>Datastore results:</h3>"); List<String> listOfKeys = new ArrayList<String>(); Query q = new Query("TaskData"); PreparedQuery pq = datastore.prepare(q); for (Entity result : pq.asIterable()) { String datastore_key = result.getKey().getName(); String taskData_value = (String) result.getProperty("value"); Date taskData_date = (Date) result.getProperty("date"); resp.getWriter() .println( "<p>keyname = " + datastore_key + " value = " + taskData_value + " date = " + taskData_date.toString() + "</p>"); listOfKeys.add(datastore_key); } // check which of the keys exist in memcache String memcache_value; resp.getWriter().println("<h3>Memcache results:</h3>"); for (String datastore_key : listOfKeys) { memcache_value = (String) syncCache.get(datastore_key); if (memcache_value != null) { // String decoded = new String(memcache_value, "UTF-8"); resp.getWriter() .println("<p>keyname = " + datastore_key + " value = " + memcache_value + "</p>"); } } } // display element of kind TaskData with key=keyname else if (keyname != null && value == null) { // first check in the cache String memcache_value = (String) syncCache.get(keyname); // Read from cache. // Get value from datastore Key task_key = KeyFactory.createKey("TaskData", keyname); try { Entity tne = datastore.get(task_key); if (memcache_value == null) { resp.getWriter().println("<h2>Datastore</h2>"); } else { resp.getWriter().println("<h2>Both</h2>"); } } catch (EntityNotFoundException e) { resp.getWriter().println("<h2>Neither</h2>"); } } // store element of kind TaskData with key=keyname and value=value else if (keyname != null && value != null) { Entity tne = new Entity("TaskData", keyname); tne.setProperty("value", value); tne.setProperty("date", new Date()); datastore.put(tne); syncCache.put(keyname, value); // Populate cache. resp.getWriter() .println("<h2>Stored " + keyname + " and " + value + " in Datastore and Memcache</h2>"); } else { resp.getWriter().println("<h2>You entered wrong query parameters</h2>"); } /* Entity tne = new Entity("TaskData", "Person"); alice.setProperty("gender", "female"); alice.setProperty("age", 20); */ resp.getWriter().println("</body></html>"); }
/** * Returns the key associated with the given alias, using the given password to recover it. * * @param alias the alias name * @param password the password for recovering the key. This password is used internally as the * key is exported in a PKCS12 format. * @return the requested key, or null if the given alias does not exist or does not identify a * <i>key entry</i>. * @exception NoSuchAlgorithmException if the algorithm for recovering the key cannot be found * @exception UnrecoverableKeyException if the key cannot be recovered (e.g., the given password * is wrong). */ public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { permissionCheck(); // An empty password is rejected by MacOS API, no private key data // is exported. If no password is passed (as is the case when // this implementation is used as browser keystore in various // deployment scenarios like Webstart, JFX and applets), create // a dummy password so MacOS API is happy. if (password == null || password.length == 0) { // Must not be a char array with only a 0, as this is an empty // string. if (random == null) { random = new SecureRandom(); } password = Long.toString(random.nextLong()).toCharArray(); } Object entry = entries.get(alias.toLowerCase()); if (entry == null || !(entry instanceof KeyEntry)) { return null; } // This call gives us a PKCS12 bag, with the key inside it. byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry) entry).keyRef, password); if (exportedKeyInfo == null) { return null; } PrivateKey returnValue = null; try { byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo); byte[] encryptedKey; AlgorithmParameters algParams; ObjectIdentifier algOid; try { // get the encrypted private key EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData); encryptedKey = encrInfo.getEncryptedData(); // parse Algorithm parameters DerValue val = new DerValue(encrInfo.getAlgorithm().encode()); DerInputStream in = val.toDerInputStream(); algOid = in.getOID(); algParams = parseAlgParameters(in); } catch (IOException ioe) { UnrecoverableKeyException uke = new UnrecoverableKeyException( "Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe); uke.initCause(ioe); throw uke; } // Use JCE to decrypt the data using the supplied password. SecretKey skey = getPBEKey(password); Cipher cipher = Cipher.getInstance(algOid.toString()); cipher.init(Cipher.DECRYPT_MODE, skey, algParams); byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey); PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey); // Parse the key algorithm and then use a JCA key factory to create the private key. DerValue val = new DerValue(decryptedPrivateKey); DerInputStream in = val.toDerInputStream(); // Ignore this -- version should be 0. int i = in.getInteger(); // Get the Algorithm ID next DerValue[] value = in.getSequence(2); AlgorithmId algId = new AlgorithmId(value[0].getOID()); String algName = algId.getName(); // Get a key factory for this algorithm. It's likely to be 'RSA'. KeyFactory kfac = KeyFactory.getInstance(algName); returnValue = kfac.generatePrivate(kspec); } catch (Exception e) { UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage()); uke.initCause(e); throw uke; } return returnValue; }
public void perform(ClassLoader loader) throws Throwable { KeyFactory.create(loader, MyKey.class, null); }
public void testSimple() throws Exception { MyKey mykey = (MyKey) KeyFactory.create(MyKey.class); assertTrue( mykey.newInstance(5, new int[] {6, 7}, false).hashCode() == mykey.newInstance(5, new int[] {6, 7}, false).hashCode()); }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { int index; DatastoreService ds; MemcacheService ms; Cookie[] cookies; boolean insideFlag; String delpw; String paramOffset; String paramSize; int offset; int size; Key postObjGroupKey; Query q; List<Entity> postObjList; PostObj postObj; Gson gson; List<String> filelinkList; resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain"); ds = DatastoreServiceFactory.getDatastoreService(); ms = MemcacheServiceFactory.getMemcacheService(); insideFlag = false; try { cookies = req.getCookies(); if (cookies.length > 0) { if (ms.contains(cookies[0].getValue()) == true) { insideFlag = true; } } } catch (Exception e) { insideFlag = false; } delpw = req.getParameter("delpw"); if (delpw != null) { if (delpw.equals("") == true) { delpw = null; } } paramOffset = req.getParameter("offset"); if (paramOffset != null) { offset = Integer.valueOf(paramOffset); } else { offset = 0; } paramSize = req.getParameter("size"); if (paramSize != null) { size = Integer.valueOf(paramSize); } else { size = 4096; } postObjGroupKey = KeyFactory.createKey("PostObjGroup", 1L); q = new Query("PostObj", postObjGroupKey); if (delpw != null) { q.addFilter("delpw", FilterOperator.EQUAL, delpw); q.addSort("delpw"); } q.addSort("posttime", SortDirection.DESCENDING); postObjList = ds.prepare(q).asList(FetchOptions.Builder.withOffset(offset).limit(size)); postObj = new PostObj(); filelinkList = new ArrayList<String>(); for (index = 0; index < postObjList.size(); index++) { postObj.getDB(postObjList.get(index)); if ((postObj.flag.equals("showgallery") == false && insideFlag == true) || (postObj.flag.equals("showgallery") == true && insideFlag == false) || delpw != null) { filelinkList.add(postObj.filelink); } } gson = new Gson(); resp.getWriter().print(gson.toJson(filelinkList)); }