Ejemplo n.º 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) {
        }
      }
    }
  }
Ejemplo n.º 2
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;
 }
Ejemplo n.º 3
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;
    }
  }
Ejemplo n.º 4
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;
 }
Ejemplo n.º 5
0
 /**
  * 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);
 }
Ejemplo n.º 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());
  }
Ejemplo n.º 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;
 }
Ejemplo n.º 9
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);
 }
Ejemplo n.º 10
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);
    }
  }
Ejemplo n.º 11
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);
 }
Ejemplo n.º 12
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());
   }
 }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
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;
   }
 }
Ejemplo n.º 16
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();
    }
  }
Ejemplo n.º 18
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;
 }
Ejemplo n.º 19
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;
   }
 }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 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;
   }
 }
Ejemplo n.º 22
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;
      }
    }
 /**
  * 对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);
   }
 }
Ejemplo n.º 24
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();
   }
 }
 /** 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;
 }
Ejemplo n.º 26
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;
 }
Ejemplo n.º 27
0
  public static String decryptTripleDes(String data) throws Exception {

    byte[] tdesKeyData = SECURITY_KEY.getBytes();

    Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
    IvParameterSpec ivspec = new IvParameterSpec(KEY_DATA_DES);

    c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec);
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] inputBytes1 = decoder.decodeBuffer(data);
    byte[] outputBytes2 = c3des.doFinal(inputBytes1);
    return new String(outputBytes2, KEY_CHARSET_UTF8);
  }
Ejemplo n.º 28
0
 // 解密:以String密文输入,String明文输出
 public void setDesString(String strMi) {
   BASE64Decoder base64De = new BASE64Decoder();
   try {
     this.byteMi = base64De.decodeBuffer(strMi);
     this.byteMing = this.getDesCode(byteMi);
     this.strM = new String(byteMing, "UTF8");
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     base64De = null;
     byteMing = null;
     byteMi = null;
   }
 }
Ejemplo n.º 29
0
  public static BufferedImage decodeImage(String imageString) {
    BufferedImage image = null;

    byte[] imageByte;
    try {
      BASE64Decoder decoder = new BASE64Decoder();
      imageByte = decoder.decodeBuffer(imageString);
      ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
      image = ImageIO.read(bis);
      bis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return image;
  }
Ejemplo n.º 30
0
  public static String decrypt(String encstr) {

    if (encstr.length() > 12) {
      String cipher = encstr.substring(12);
      BASE64Decoder decoder = new BASE64Decoder();

      try {
        return new String(decoder.decodeBuffer(cipher));
      } catch (IOException e) {

        e.printStackTrace();
      }
    }

    return null;
  }