public String handleResource(HtmlResource resource) throws IOException {
    char[] base64Data = new char[0];
    byte[] data = resource.getData();
    if (data != null) base64Data = Base64Coder.encode(data);

    return String.format("data:%s;base64,%s", resource.getMimeType(), new String(base64Data));
  }
Example #2
0
 public static String sign(String s, String privkey) {
   String r = null;
   PrivateKey myprikey = null;
   byte[] bs = Base64Coder.decode(privkey.toCharArray());
   PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bs);
   try {
     myprikey = KeyFactory.getInstance("DSA").generatePrivate(spec);
     Signature signet = Signature.getInstance("DSA");
     signet.initSign(myprikey);
     byte[] b = s.getBytes();
     signet.update(b, 0, b.length);
     byte[] signed = signet.sign();
     r = new String(Base64Coder.encode(signed));
   } catch (Throwable e) {
   }
   return r;
 }
Example #3
0
  public String decrypt(String str) throws Exception {
    // return SimpleCrypto.decrypt(this.key, str);

    // Decode base64 to get bytes
    byte[] dec = Base64Coder.decode(str);

    byte[] utf8 = dcipher.doFinal(dec);

    // Decode using utf-8
    return new String(utf8, "UTF8");
  }
Example #4
0
  @Override
  public void saveStatistics(es.danirod.rectball.model.Statistics statistics) {
    Json json = new Json();
    json.setOutputType(JsonWriter.OutputType.json);
    String jsonData = json.toJson(statistics);

    // Encode statistics in Base64 and save it to a file.
    String encodedJson = Base64Coder.encodeString(jsonData);
    FileHandle handle;
    handle = getStatistics();
    handle.writeString(encodedJson, false);
  }
 // Test Base64Coder against sun.misc.BASE64Encoder/Decoder with
 // random strings.
 private static void test2() throws Exception {
   System.out.println("test2 started");
   sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
   sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
   java.util.Random rnd = new java.util.Random(0x538afb92);
   for (int i = 0; i < 50000; i++) {
     int len = rnd.nextInt(55);
     byte[] b0 = new byte[len];
     rnd.nextBytes(b0);
     String e1 = new String(Base64Coder.encode(b0));
     String e2 = enc.encode(b0);
     if (!e1.equals(e2))
       System.out.println(
           "Error\ne1=" + e1 + " len=" + e1.length() + "\ne2=" + e2 + " len=" + e2.length());
     byte[] b1 = Base64Coder.decode(e1);
     byte[] b2 = dec.decodeBuffer(e2);
     if (!compareByteArrays(b1, b0) || !compareByteArrays(b2, b0))
       System.out.println("Decoded data not equal. len1=" + b1.length + " len2=" + b2.length);
   }
   System.out.println("test2 completed");
 }
  public static void main(String arg[]) {
    String enc = encrypt("Eko SW", "eko");
    String dec = decrypt(enc, "eko");
    System.out.println("enc=" + enc);
    System.out.println("dec=" + dec);
    String enc64 = toBase64String(enc.getBytes());
    System.out.println("enc64=" + enc64);
    System.out.println("dec64=" + fromBase64String(enc64));
    String x = base64Encode(enc);
    System.out.println("encode=" + x);
    byte[] y = fromBase64String(x);
    System.out.println(y.toString());

    originalText = "Eko SW";
    String s1 = Base64Coder.encodeString(enc);
    String s2 = Base64Coder.decodeString(s1);
    System.out.println(enc + "," + s1 + "," + s2);
    String k = Base64Coder.decodeString("yUfOSMUbZ58=");
    String l = decrypt(k, "eko");
    System.out.println("xx=" + l);
  }
Example #7
0
 /**
  * 上传
  *
  * @param pathList
  */
 public static void upload(List<String> pathList, String url) {
   String files = "FileUpload:";
   url = NetManager.HTTP_DOMAIN + url;
   for (int i = 0; i < pathList.size(); i++) {
     Log.i("HttpUrlEncodedFormEntityPost", "filePath:" + pathList.get(i));
     // 根据路径生成一个Bitmap
     Bitmap tBitmap = convertToBitmap(pathList.get(i), 400, 400);
     // 把Bitmap写进流里面
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     tBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
     // 把流转化为数组
     byte[] b = stream.toByteArray();
     // 将图片流以字符串形式存储下来
     String file = new String(Base64Coder.encodeLines(b));
     // 设置一条分割线
     files += "---------------------------7da2137580612";
     // 累加每一个文件转化成的String数据
     files += file;
   }
   HttpClient client = new DefaultHttpClient();
   // 设置上传参数
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   formparams.add(new BasicNameValuePair("file", files));
   HttpPost post = new HttpPost(url);
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams, "UTF-8");
     post.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml");
     post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
     post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
     post.addHeader("Connection", "Keep-Alive");
     post.addHeader("Cache-Control", "no-cache");
     String BOUNDARY = "----------" + System.currentTimeMillis();
     post.setHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
     // post.addHeader("Content-Type", "multipart/form-data");
     post.setEntity(entity);
     HttpResponse response = client.execute(post);
     Log.v(
         "HttpUrlEncodedFormEntityPost",
         "StatusCode: " + response.getStatusLine().getStatusCode());
     HttpEntity e = response.getEntity();
     Log.v("HttpUrlEncodedFormEntityPost", "response :" + EntityUtils.toString(e));
     if (200 == response.getStatusLine().getStatusCode()) {
       // Toast.makeTast(Activity,"上传完成",1000).show;
     } else {
       // Toast.makeTast(Activity,"上传失败",1000).show();
     }
     client.getConnectionManager().shutdown();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #8
0
  public String encrypt(String str) throws Exception {

    // return SimpleCrypto.encrypt(this.key, str);

    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");

    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);

    // Encode bytes to base64 to get a string
    return Base64Coder.encode(enc);
  }
Example #9
0
  @Override
  public es.danirod.rectball.model.Statistics loadStatistics() {
    try {
      // Read stats from file and decode them.
      FileHandle handle = getStatistics();
      String encodedJson = handle.readString();
      String decodedJson = Base64Coder.decodeString(encodedJson);

      // Convert JSON to statistics
      Json json = new Json();
      return json.fromJson(es.danirod.rectball.model.Statistics.class, decodedJson);
    } catch (Exception ex) {
      return new es.danirod.rectball.model.Statistics();
    }
  }
 public static void main(String[] args) {
   try {
     byte[] wav = Base64Coder.base64ToBinary(getWaveLiteral().toCharArray(), 0, WAV_SIZE);
     InputStream is = new ByteArrayInputStream(wav);
     AudioFormat fmt = AudioSystem.getAudioFileFormat(is).getFormat();
     AudioInputStream sound = AudioSystem.getAudioInputStream(is);
     DataLine.Info info = new DataLine.Info(Clip.class, fmt);
     Clip clip = (Clip) AudioSystem.getLine(info);
     clip.open(sound);
     clip.start();
     Thread.sleep(3000);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
Example #11
0
 public void upload() {
   ByteArrayOutputStream stream = new ByteArrayOutputStream();
   String picPath = "";
   Bitmap upbitmap = new BitmapFactory().decodeFile(picPath);
   upbitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
   byte[] b = stream.toByteArray();
   // 将图片流以字符串形式存储下来
   String file = new String(Base64Coder.encodeLines(b));
   HttpClient client = new DefaultHttpClient();
   // 设置上传参数
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   formparams.add(new BasicNameValuePair("contract", file));
   formparams.add(new BasicNameValuePair("buyMoney", "213"));
   HttpPost post = new HttpPost(URLs.FEEDBACK_URL);
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams, "UTF-8");
     post.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml");
     post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
     post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
     post.addHeader("Connection", "Keep-Alive");
     post.addHeader("Cache-Control", "no-cache");
     post.addHeader("Content-Type", "application/x-www-form-urlencoded");
     post.setEntity(entity);
     HttpResponse response = client.execute(post);
     System.out.println(response.getStatusLine().getStatusCode());
     HttpEntity e = response.getEntity();
     System.out.println(EntityUtils.toString(e));
     if (200 == response.getStatusLine().getStatusCode()) {
       System.out.println("上传完成");
     } else {
       System.out.println("上传失败");
     }
     client.getConnectionManager().shutdown();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @Test
 public void encodeOneNegativeByte() {
   assertEquals("/w==", Base64Coder.encode(new byte[] {-1}));
 }
Example #13
0
  /**
   * Call method with optional parameters. This is general method. If you want to call your method
   * with 0-8 parameters, you can use more convenience call() methods
   *
   * @param method name of method to call
   * @param params parameters to pass to method (may be null if method has no parameters)
   * @return deserialized method return value
   * @throws XMLRPCException
   */
  @SuppressWarnings("unchecked")
  public Object callEx(String method, Object[] params) throws XMLRPCException {
    try {
      // prepare POST body
      String body = methodCall(method, params);

      // set POST body
      HttpEntity entity = new StringEntity(body);
      postMethod.setEntity(entity);

      // This code slightly tweaked from the code by erickok in issue #6
      // Force preemptive authentication
      // This makes sure there is an 'Authentication: ' header being send before trying and failing
      // and retrying
      // by the basic authentication mechanism of DefaultHttpClient
      if (this.httpPreAuth == true) {
        String auth = this.username + ":" + this.password;
        postMethod.addHeader(
            "Authorization", "Basic " + Base64Coder.encode(auth.getBytes()).toString());
      }

      // Log.d(Tag.LOG, "ros HTTP POST");
      // execute HTTP POST request
      HttpResponse response = client.execute(postMethod);
      // Log.d(Tag.LOG, "ros HTTP POSTed");

      // check status code
      int statusCode = response.getStatusLine().getStatusCode();
      // Log.d(Tag.LOG, "ros status code:" + statusCode);
      if (statusCode != HttpStatus.SC_OK) {
        throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
      }

      // parse response stuff
      //
      // setup pull parser
      XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
      entity = response.getEntity();
      Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent()));
      // for testing purposes only
      // reader = new StringReader("<?xml
      // version='1.0'?><methodResponse><params><param><value>\n\n\n</value></param></params></methodResponse>");
      pullParser.setInput(reader);

      // lets start pulling...
      pullParser.nextTag();
      pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE);

      pullParser.nextTag(); // either Tag.PARAMS (<params>) or Tag.FAULT (<fault>)
      String tag = pullParser.getName();
      if (tag.equals(Tag.PARAMS)) {
        // normal response
        pullParser.nextTag(); // Tag.PARAM (<param>)
        pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM);
        pullParser.nextTag(); // Tag.VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize result
        Object obj = iXMLRPCSerializer.deserialize(pullParser);
        entity.consumeContent();
        return obj;
      } else if (tag.equals(Tag.FAULT)) {
        // fault response
        pullParser.nextTag(); // Tag.VALUE (<value>)
        // no parser.require() here since its called in XMLRPCSerializer.deserialize() below

        // deserialize fault result
        Map<String, Object> map = (Map<String, Object>) iXMLRPCSerializer.deserialize(pullParser);
        String faultString = (String) map.get(Tag.FAULT_STRING);
        int faultCode = (Integer) map.get(Tag.FAULT_CODE);
        entity.consumeContent();
        throw new XMLRPCFault(faultString, faultCode);
      } else {
        entity.consumeContent();
        throw new XMLRPCException(
            "Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
      }
    } catch (XMLRPCException e) {
      // catch & propagate XMLRPCException/XMLRPCFault
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      // wrap any other Exception(s) around XMLRPCException
      throw new XMLRPCException(e);
    }
  }
 @Test
 public void encodeLenIs1Mod3() {
   assertEquals("Q2F0cw==", Base64Coder.encode(new byte[] {'C', 'a', 't', 's'}));
 }
 @Test
 public void decodeLenIs1Mod3() {
   assertArrayEquals(new byte[] {'C', 'a', 't', 's'}, Base64Coder.decodeBytes("Q2F0cw=="));
 }
 @Test
 public void encodeLenIs2Mod3() {
   assertEquals("QnJhaW4=", Base64Coder.encode(new byte[] {'B', 'r', 'a', 'i', 'n'}));
 }
 @Test
 public void decodeTwoNegativeBytes() {
   assertArrayEquals(new byte[] {-1, -1}, Base64Coder.decodeBytes("//8="));
 }
 @Test
 public void decodeLenIs2Mod3() {
   assertArrayEquals(new byte[] {'B', 'r', 'a', 'i', 'n'}, Base64Coder.decodeBytes("QnJhaW4="));
 }
 public static String safeEncrypt(String plainText, String password) {
   return Base64Coder.encodeString(encrypt(plainText, password));
 }
 @Test
 public void negativeDecodeBug() {
   assertArrayEquals(new byte[] {-1, 0, -1}, Base64Coder.decodeBytes("/wD/"));
 }
 @Test
 public void decodeOneNegativeByte() {
   assertArrayEquals(new byte[] {-1}, Base64Coder.decodeBytes("/w=="));
 }
 @Test
 public void encodeTwoNegativeBytes() {
   assertEquals("//8=", Base64Coder.encode(new byte[] {-1, -1}));
 }
 public static String safeDecrypt(String cryptedText, String password) {
   return decrypt(Base64Coder.decodeString(cryptedText), password);
 }
Example #24
0
 private static void check(String plainText, String base64Text) {
   String s1 = Base64Coder.encodeString(plainText);
   String s2 = Base64Coder.decodeString(base64Text);
   if (!s1.equals(base64Text) || !s2.equals(plainText))
     System.out.println("check failed for \"" + plainText + "\" / \"" + base64Text + "\".");
 }