Example #1
0
  /**
   * 写入文件,如果已存在则删除
   *
   * @param storePath
   * @param imgStr
   * @return
   */
  public static boolean decodeImage(String storePath, String imgStr) {
    if (imgStr == null) return false;
    BASE64Decoder decoder = new BASE64Decoder();
    OutputStream out = null;

    File file = new File(storePath);
    if (file.exists()) file.delete();
    try {
      // Base64解码
      byte[] b = decoder.decodeBuffer(imgStr);
      for (int i = 0; i < b.length; ++i) {
        if (b[i] < 0) { // 调整异常数据
          b[i] += 256;
        }
      }
      out = new FileOutputStream(storePath);
      out.write(b);
      out.flush();
      return true;
    } catch (Exception e) {
      if (Global.DEBUG) {
        e.printStackTrace();
      }
      return false;
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
        }
      }
    }
  }
Example #2
0
 /**
  * Description 根据键值进行解密
  *
  * @param data
  * @param key 加密键byte数组
  * @return
  * @throws IOException
  * @throws Exception
  */
 public static String decrypt(String data, String key) throws IOException, Exception {
   if (data == null) return null;
   BASE64Decoder decoder = new BASE64Decoder();
   byte[] buf = decoder.decodeBuffer(data);
   byte[] bt = decrypt(buf, key.getBytes());
   return new String(bt);
 }
Example #3
0
 /**
  * Generates Public Key from BASE64 encoded string
  *
  * @param key BASE64 encoded string which represents the key
  * @return The PublicKey
  * @throws java.lang.Exception
  */
 public static PublicKey getPublicKeyFromString(String key) throws Exception {
   BASE64Decoder b64 = new BASE64Decoder();
   KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
   EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64.decodeBuffer(key));
   PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
   return publicKey;
 }
Example #4
0
  public static boolean verifySign(String certName, String base64Sign, String src) {
    boolean b = false;
    try {
      InputStream is = new FileInputStream(certName);
      CertificateFactory cf = CertificateFactory.getInstance("x509");
      Certificate cerCert = cf.generateCertificate(is);
      PublicKey publicKey = cerCert.getPublicKey();

      BASE64Decoder de = new BASE64Decoder();
      String tmp = base64Sign.replaceAll(" ", "+");
      byte[] byteSign = de.decodeBuffer(tmp);
      byte[] oldMD5 = rsaDecrypt(publicKey, byteSign);
      byte[] newMD5 = UnionPayMd5.MD5(src);
      if (oldMD5.length == newMD5.length) {
        int i = 0;
        for (i = 0; i < oldMD5.length; i++) {
          if (oldMD5[i] == newMD5[i]) {
            System.out.println("123");
            continue;
          } else {
            break;
          }
        }
        if (i == oldMD5.length) {
          b = true;
        }
      }
      return b;
    } catch (Exception e) {
      e.printStackTrace();
      return b;
    }
  }
 /**
  * Methot that decrypts a value.
  *
  * @param value
  * @return
  * @throws InvalidKeyException
  * @throws IllegalBlockSizeException
  * @throws BadPaddingException
  * @throws IOException
  */
 public String decrypt(String value)
     throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
   cipher.init(Cipher.DECRYPT_MODE, secretKey);
   BASE64Decoder dec = new BASE64Decoder();
   byte[] decipherText = cipher.doFinal(dec.decodeBuffer(value));
   return new String(decipherText);
 }
Example #6
0
  public FileData decryptFile(FileData fd) throws IOException {
    ByteArrayInputStream input = fd.getInputStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    BASE64Decoder base64 = new BASE64Decoder();
    byte[] bytearr = base64.decodeBuffer(input);
    input = new ByteArrayInputStream(bytearr);

    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    } catch (Exception e) {
      throw new IOException(e);
    }

    try {
      cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
      throw new IOException(e);
    }

    int length = -1;
    CipherInputStream stream = new CipherInputStream(input, cipher);
    while ((length = stream.read(bytearr)) != -1) {
      output.write(bytearr, 0, length);
    }
    output.close();

    String path = fd.getPath().replaceAll("\\.(.*)_enc", "\\.$1");
    return new FileData(path, output.toByteArray());
  }
Example #7
0
  /*
   * 解析站内应用post的SignedRequest split为part1和part2两部分
   */
  public String parseSignedRequest(String signed_request)
      throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    String[] t = signed_request.split("\\.", 2);
    // 为了和 url encode/decode 不冲突,base64url 编码方式会将
    // '+','/'转换成'-','_',并且去掉结尾的'='。 因此解码之前需要还原到默认的base64编码,结尾的'='可以用以下算法还原
    int padding = (4 - t[0].length() % 4);
    for (int i = 0; i < padding; i++) t[0] += "=";
    String part1 = t[0].replace("-", "+").replace("_", "/");

    SecretKey key =
        new SecretKeySpec(WeiboConfig.getValue("client_SERCRET").getBytes(), "hmacSHA256");
    Mac m;
    m = Mac.getInstance("hmacSHA256");
    m.init(key);
    m.update(t[1].getBytes());
    String part1Expect = BASE64Encoder.encode(m.doFinal());

    sun.misc.BASE64Decoder decode = new sun.misc.BASE64Decoder();
    String s = new String(decode.decodeBuffer(t[1]));
    if (part1.equals(part1Expect)) {
      return ts(s);
    } else {
      return null;
    }
  }
 private void setHPubAccessHandleString(String encodedHandleWithSpaces) {
   String encodedHandle = removeSpaceCharacters(encodedHandleWithSpaces);
   if ((encodedHandle == null) || (encodedHandle.length() < 5)) {
     return;
   }
   try {
     byte[] handleByteArray = null;
     sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
     try {
       handleByteArray = dec.decodeBuffer(encodedHandle);
     } catch (Exception e) {
       System.out.println("AccessEJBTemplate::setHPubAccessHandleString()  decoding buffer");
     }
     ;
     ByteArrayInputStream bais = new ByteArrayInputStream(handleByteArray);
     javax.ejb.Handle h1 = null;
     try {
       ObjectInputStream ois = new ObjectInputStream(bais);
       hPubAccessHandle = (javax.ejb.Handle) ois.readObject();
     } catch (Exception ioe) {
       System.out.println("Exception reading handle object");
     }
   } catch (Exception e) {
     e.printStackTrace(System.err);
     System.out.println("Exception AccessEJBTemplate::setHPubAccessHandleString()");
   }
   return;
 }
Example #9
0
 /**
  * 将BASE64加密字符串转换为图片
  *
  * @param base64String
  * @param imagePath 图片生成路径
  * @param format 图片格式
  */
 public void convertBase64ToImage(String base64String, String imagePath, String format) {
   byte[] bytes = null;
   ByteArrayInputStream bais = null;
   BufferedImage bi = null;
   File file = null;
   try {
     bytes = decoder.decodeBuffer(base64String);
     bais = new ByteArrayInputStream(bytes);
     bi = ImageIO.read(bais);
     file = new File(imagePath);
     ImageIO.write(bi, format == null ? IMAGE_TYPE : format, file);
     logger.info("将BASE64加密字符串转换为图片成功!");
   } catch (Exception e) {
     logger.error("将BASE64加密字符串转换为图片失败:" + e);
   } finally {
     try {
       if (bais != null) {
         bais.close();
         bais = null;
       }
     } catch (Exception e) {
       logger.error("关闭文件流发生异常:" + e);
     }
   }
 }
Example #10
0
 /**
  * Generates Private Key from BASE64 encoded string
  *
  * @param key BASE64 encoded string which represents the key
  * @return The PrivateKey
  * @throws java.lang.Exception
  */
 public static PrivateKey getPrivateKeyFromString(String key) throws Exception {
   KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
   BASE64Decoder b64 = new BASE64Decoder();
   EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64.decodeBuffer(key));
   PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
   return privateKey;
 }
Example #11
0
  public void initSiteEncryptionService() throws Exception {
    try {
      FileInputStream fis = new FileInputStream(secFile);
      Properties props = new Properties();
      props.load(fis);
      String k = props.getProperty("k");
      String d = props.getProperty("d");
      sun.misc.BASE64Decoder bde = new sun.misc.BASE64Decoder();
      // Decrypt the key
      byte[] key = decrypt(basePair.getDecryptor(), k);
      byte[] digest = bde.decodeBuffer(d);
      md5.reset();
      byte[] d2 = md5.digest(key);
      if (!Arrays.equals(digest, d2)) {
        throw (Exception) new Exception("FATAL -- Tampered key");
      }
      sitePair = initCiphers(key);

      // Get rid of the base pair

      basePair.setEncryptor(null);
      basePair.setDecryptor(null);
      basePair = null;
    } catch (FileNotFoundException fnfe) {
      throw (Exception)
          new Exception("Encryption utility not installed under current TRAFCIHOME")
              .initCause(fnfe);

    } catch (IOException ioe) {
      throw (Exception) new Exception("IO Exception").initCause(ioe);
    }
  }
Example #12
0
 /**
  * Description:对BASE64加密后的字符串进行解密
  *
  * @author chenqi
  * @version 1.0
  * @param str 需解密的字符串
  * @return 返回解密后的字符串
  * @throws IOException
  */
 private static String unEncrypt(String str) throws IOException {
   if (str == null || str.equals("")) {
     return "";
   }
   BASE64Decoder decoder = new BASE64Decoder();
   byte[] b = decoder.decodeBuffer(str);
   return new String(b);
 }
Example #13
0
 /**
  * @param base64
  * @return
  */
 public static byte[] decode(String base64) {
   BASE64Decoder decoder = new BASE64Decoder();
   try {
     return decoder.decodeBuffer(base64);
   } catch (IOException io) {
     throw new RuntimeException(io.getMessage(), io.getCause());
   }
 }
 /**
  * Decode a string using Base64 encoding.
  *
  * @param str
  * @return String
  */
 public static String decodeString(String str) {
   sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
   try {
     return new String(dec.decodeBuffer(str));
   } catch (IOException io) {
     throw new RuntimeException(io.getMessage(), io.getCause());
   }
 }
Example #15
0
  public static boolean valid(String signData) throws Exception {

    System.out.println(signData);
    PublicKey publicKey = getCaCert().getPublicKey();
    Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initVerify(publicKey);
    sig.update(getSignData().getBytes());
    return sig.verify(decoder.decodeBuffer(signData));
  }
Example #16
0
  /**
   * decoding
   *
   * @param b64Str String
   * @return String
   * @throws Exception
   */
  protected String decoding(String b64Str) throws Exception {

    String result = "";
    sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    byte[] b1 = decoder.decodeBuffer(b64Str);
    result = new String(b1);

    return result;
  }
Example #17
0
 /**
  * From a base 64 representation, returns the corresponding byte[].
  *
  * @param data The base 64 representation.
  * @return The byte[] representation of given String.
  */
 static byte[] base64ToByte(String data) {
   try {
     BASE64Decoder decoder = new BASE64Decoder();
     return decoder.decodeBuffer(data);
   } catch (IOException e) {
     // Shuold never happen.
     return null;
   }
 }
Example #18
0
 private String decrypt(String s) {
   try {
     byte[] encrypted = b64Decoder.decodeBuffer(s);
     byte[] decrypted = deCipher.doFinal(encrypted);
     return new String(decrypted);
   } catch (Exception ex) {
     return "error";
   }
 }
Example #19
0
 public static byte[] base64ToBytes(String b64str) {
   try {
     BASE64Decoder b64decoder = new BASE64Decoder();
     return b64decoder.decodeBuffer(b64str);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return null;
 }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    try {
      String engineURL = req.getParameter("url");

      String user = req.getHeader("Authorization");
      if (user != null) {
        java.util.StringTokenizer st = new java.util.StringTokenizer(user);
        if (st.hasMoreTokens()) {
          if (st.nextToken().equalsIgnoreCase("Basic")) {
            BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            String userPass = new String(decoder.decodeBuffer(st.nextToken()));
            user = userPass.split(":")[0];
          }
        }
      }

      if (user == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Please type in your username here\"");
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
      }

      URL url_engine = new URL(engineURL);
      HttpURLConnection connection_engine = (HttpURLConnection) url_engine.openConnection();
      connection_engine.setRequestMethod("GET");
      String encoding = new sun.misc.BASE64Encoder().encode((user + ":").getBytes());
      connection_engine.setRequestProperty("Authorization", "Basic " + encoding);
      connection_engine.setDoInput(true);

      connection_engine.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection_engine.setRequestProperty(
          "Accept",
          "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

      connection_engine.connect();

      if (connection_engine.getResponseCode() == 200) {
        DataInputStream in = new DataInputStream(connection_engine.getInputStream());
        String str;
        String xmlDoc = "";
        while ((str = in.readLine()) != null) {
          xmlDoc += str + " ";
        }
        /*
        				xmlDoc = xmlDoc.replaceAll("href=\"/", "href=\"/oryx/engineproxy?url="+url_engine.getProtocol()+"://"+url_engine.getHost()+":"+url_engine.getPort()+"/");
        				xmlDoc = xmlDoc.replaceAll("src=\"/", "src=\"/oryx/engineproxy?url="+url_engine.getProtocol()+"://"+url_engine.getHost()+":"+url_engine.getPort()+"/");
        				xmlDoc = xmlDoc.replaceAll("action=\"/", "action=\"/oryx/engineproxy?url="+url_engine.getProtocol()+"://"+url_engine.getHost()+":"+url_engine.getPort()+"/");
        */
        PrintWriter out = resp.getWriter();

        out.print(xmlDoc);
      }
    } catch (Exception e1) {
      e1.printStackTrace();
    }
  }
Example #21
0
 // �?BASE64 编码的字符串 s 进行解码
 public static String getFromBASE64(String s) {
   if (s == null) return null;
   BASE64Decoder decoder = new BASE64Decoder();
   try {
     byte[] b = decoder.decodeBuffer(s);
     return new String(b, "UTF-8");
   } catch (Exception e) {
     return null;
   }
 }
Example #22
0
 // �?BASE64 编码的字符串 s 进行解码
 public static byte[] getBytesBASE64(String s) {
   if (s == null) return null;
   BASE64Decoder decoder = new BASE64Decoder();
   try {
     byte[] b = decoder.decodeBuffer(s);
     return b;
   } catch (Exception e) {
     return null;
   }
 }
Example #23
0
 public static byte[] base64Decode(String str) {
   byte[] bt = null;
   try {
     sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
     bt = decoder.decodeBuffer(str);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bt;
 }
Example #24
0
 /**
  * 将字符串转换为DES算法可以解密的byte数组.
  *
  * @param datasource the datasource
  * @return the byte[]
  */
 public byte[] stringToByte(String datasource) {
   BASE64Decoder bd = new BASE64Decoder();
   byte[] sorData = null;
   try {
     sorData = bd.decodeBuffer(datasource);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return sorData;
 }
Example #25
0
    private byte[] base64Decode(String data) {
      if (data == null) return null;

      BASE64Decoder dec = new BASE64Decoder();
      try {
        return dec.decodeBuffer(data);
      } catch (IOException e) {
        logger.warn("Couldn't decode form [ " + data + " ] for base64");
        return null;
      }
    }
Example #26
0
 public static void base64() {
   BASE64Encoder encoder = new BASE64Encoder();
   BASE64Decoder decoder = new BASE64Decoder();
   try {
     String encodedBytes = encoder.encodeBuffer("JavaTips.net".getBytes());
     System.out.println("encodedBytes " + encodedBytes);
     byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
     System.out.println("decodedBytes " + new String(decodedBytes));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * 对str进行DES解密
  *
  * @param str
  * @return
  */
 public static String getDecryptString(String str) {
   BASE64Decoder base64De = new BASE64Decoder();
   try {
     byte[] strBytes = base64De.decodeBuffer(str);
     Cipher cipher = Cipher.getInstance("DES");
     cipher.init(Cipher.DECRYPT_MODE, key);
     byte[] decryptStrBytes = cipher.doFinal(strBytes);
     return new String(decryptStrBytes, "UTF8");
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 /** Method To Decrypt An Ecrypted String */
 public String decrypt(String encryptedString) {
   String decryptedText = null;
   try {
     cipher.init(Cipher.DECRYPT_MODE, key);
     BASE64Decoder base64decoder = new BASE64Decoder();
     byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
     byte[] plainText = cipher.doFinal(encryptedText);
     decryptedText = bytes2String(plainText);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return decryptedText;
 }
Example #29
0
 /**
  * Convert Base64 encoded string to normal String
  *
  * @param str encoded String
  * @return normal UTF-8 String
  */
 public static String convertBase64ToStr(String s) {
   byte[] b = null;
   String result = null;
   if (s != null) {
     BASE64Decoder decoder = new BASE64Decoder();
     try {
       b = decoder.decodeBuffer(s);
       result = new String(b, "UTF-8");
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return result;
 }
Example #30
0
  /**
   * Decodes the given {@link String} using the Base64 decoding algorithm.
   *
   * @param stringToDecode the {@link String} to decode
   * @return a new decoded {@link String}
   */
  public static String decode(String stringToDecode) {
    if (stringToDecode == null) {
      return "";
    }

    byte[] decodedBytes;
    try {
      decodedBytes = DECODER.decodeBuffer(stringToDecode);
    } catch (IOException ioe) {
      throw new CannotDecodeException("Could not decode [" + stringToDecode + "].", ioe);
    }

    return new String(decodedBytes, Charsets.UTF_8);
  }