Exemplo n.º 1
0
  /**
   * Authenticate to the IMAP server by sending the AUTHENTICATE command with the selected
   * mechanism, using the given username and the given password.
   *
   * <p>
   *
   * @return True if successfully completed, false if not.
   * @exception IOException If an I/O error occurs while either sending a command to the server or
   *     receiving a reply from the server.
   * @exception NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the
   *     Java runtime system.
   * @exception InvalidKeyException If the CRAM hash algorithm failed to use the given password.
   * @exception InvalidKeySpecException If the CRAM hash algorithm failed to use the given password.
   */
  public boolean auth(AuthenticatingIMAPClient.AUTH_METHOD method, String username, String password)
      throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (!IMAPReply.isContinuation(sendCommand(IMAPCommand.AUTHENTICATE, method.getAuthName()))) {
      return false;
    }

    switch (method) {
      case PLAIN:
        {
          // the server sends an empty response ("+ "), so we don't have to read it.
          int result =
              sendData(
                  new String(
                      Base64.encodeBase64(("\000" + username + "\000" + password).getBytes())));
          if (result == IMAPReply.OK) {
            setState(IMAP.IMAPState.AUTH_STATE);
          }
          return result == IMAPReply.OK;
        }
      case CRAM_MD5:
        {
          // get the CRAM challenge (after "+ ")
          byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(2).trim());
          // get the Mac instance
          Mac hmac_md5 = Mac.getInstance("HmacMD5");
          hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5"));
          // compute the result:
          byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes();
          // join the byte arrays to form the reply
          byte[] usernameBytes = username.getBytes();
          byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
          System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
          toEncode[usernameBytes.length] = ' ';
          System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
          // send the reply and read the server code:
          int result = sendData(new String(Base64.encodeBase64(toEncode)));
          if (result == IMAPReply.OK) {
            setState(IMAP.IMAPState.AUTH_STATE);
          }
          return result == IMAPReply.OK;
        }
      case LOGIN:
        {
          // the server sends fixed responses (base64("Username") and
          // base64("Password")), so we don't have to read them.
          if (sendData(new String(Base64.encodeBase64(username.getBytes()))) != IMAPReply.CONT) {
            return false;
          }
          int result = sendData(new String(Base64.encodeBase64(password.getBytes())));
          if (result == IMAPReply.OK) {
            setState(IMAP.IMAPState.AUTH_STATE);
          }
          return result == IMAPReply.OK;
        }
    }
    return false; // safety check
  }
Exemplo n.º 2
0
 /**
  * 加密数据
  *
  * @param data 待加密数据
  * @param key 密钥
  * @return 加密后的数据
  */
 public static String encrypt(String data, String key) throws Exception {
   Key k = toKey(Base64.decodeBase64(key)); // 还原密钥
   // 使用PKCS7Padding填充方式,这里就得这么写了(即调用BouncyCastle组件实现)
   // Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
   Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // 实例化Cipher对象,它用于完成实际的加密操作
   cipher.init(Cipher.ENCRYPT_MODE, k); // 初始化Cipher对象,设置为加密模式
   return Base64.encodeBase64String(
       cipher.doFinal(data.getBytes())); // 执行加密操作。加密后的结果通常都会用Base64编码进行传输
 }
Exemplo n.º 3
0
 /**
  * 采用二进制公匙进行签名验证
  *
  * @param data 数据信息
  * @param publicKey 2进制公匙
  * @param signature base64编码的签名信息
  * @return
  * @throws Exception
  * @author huangbuji
  *     <p>Create at 2014-2-12 下午5:37:18
  */
 public static boolean verifyBinKey(String data, byte[] publicKey, String signature)
     throws Exception {
   Base64 base64 = new Base64();
   X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
   PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec);
   // 验证
   Signature sign = Signature.getInstance("DSA");
   sign.initVerify(pub);
   sign.update(data.getBytes("utf8"));
   // return sign.verify(decoder.decodeBuffer(signature));
   return sign.verify(base64.decode(signature.getBytes("utf8")));
 }
Exemplo n.º 4
0
 /**
  * 根据数据,生成签名
  *
  * @param data 数据信息
  * @param privateKey 私匙序列化后的base64编码
  * @return base64编码的签名信息
  * @throws Exception
  */
 public static String sign(String data, String privateKeyString) throws Exception {
   Base64 base64 = new Base64();
   // 私匙反序列化
   // BASE64Decoder decoder = new BASE64Decoder();
   // byte[] bytes = decoder.decodeBuffer(privateKeyString);
   byte[] bytes = base64.decode(privateKeyString.getBytes("utf8"));
   PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
   PrivateKey privateKey = KeyFactory.getInstance("DSA").generatePrivate(keySpec);
   // 生成签名
   Signature signature = Signature.getInstance("DSA");
   signature.initSign(privateKey);
   signature.update(data.getBytes("utf8"));
   // return new BASE64Encoder().encode(signature.sign());
   return new String(base64.encode(signature.sign()), "utf8");
 }
Exemplo n.º 5
0
 /**
  * Send the ADAT command with the specified authentication data.
  *
  * @param data The data to send with the command.
  * @return server reply.
  * @throws IOException If an I/O error occurs while sending the command.
  * @since 3.0
  */
 public int execADAT(byte[] data) throws IOException {
   if (data != null) {
     return sendCommand(CMD_ADAT, Base64.encodeBase64StringUnChunked(data));
   } else {
     return sendCommand(CMD_ADAT);
   }
 }
Exemplo n.º 6
0
 /**
  * Send the ENC command with the specified data.
  *
  * @param data The data to send with the command.
  * @return server reply.
  * @throws IOException If an I/O error occurs while sending the command.
  * @since 3.0
  */
 public int execENC(byte[] data) throws IOException {
   if (data != null) {
     return sendCommand(CMD_ENC, Base64.encodeBase64StringUnChunked(data));
   } else {
     return sendCommand(CMD_ENC, ""); // perhaps "=" or just sendCommand(String)?
   }
 }
Exemplo n.º 7
0
 /**
  * Parses the given ADAT response line and base64-decodes the data.
  *
  * @param reply The ADAT reply to parse.
  * @return the data in the reply, base64-decoded.
  * @since 3.0
  */
 public byte[] parseADATReply(String reply) {
   if (reply == null) {
     return null;
   } else {
     return Base64.decodeBase64(extractPrefixedData("ADAT=", reply));
   }
 }
Exemplo n.º 8
0
 /**
  * 验证签名
  *
  * @param data 数据信息
  * @param publicKeyString 公匙序列化后的base64编码
  * @param signature base64编码的签名信息
  * @return
  * @throws Exception
  */
 public static boolean verify(String data, String publicKeyString, String signature)
     throws Exception {
   // 公匙反序列化
   // BASE64Decoder decoder = new BASE64Decoder();
   // byte[] bytes = decoder.decodeBuffer(publicKeyString);
   Base64 base64 = new Base64();
   byte[] bytes = base64.decode(publicKeyString.getBytes("utf8"));
   X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
   PublicKey publicKey = KeyFactory.getInstance("DSA").generatePublic(keySpec);
   // 验证
   Signature sign = Signature.getInstance("DSA");
   sign.initVerify(publicKey);
   sign.update(data.getBytes("utf8"));
   // return sign.verify(decoder.decodeBuffer(signature));
   return sign.verify(base64.decode(signature.getBytes("utf8")));
 }
Exemplo n.º 9
0
 public static String encrypt(String value) {
   if (!value.isEmpty()) {
     try {
       return Base64.encodeBase64String(value.getBytes());
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return value;
 }
Exemplo n.º 10
0
  /**
   * 补充C#签名信息缺失的前面46位二进制
   *
   * @param sign base64编码的签名信息
   * @return 完整的签名二进制信息
   * @throws Exception
   * @author huangbuji
   *     <p>Create at 2014-2-13 上午10:38:46
   */
  public static byte[] changeDSANet2java(String sign) throws Exception {
    Base64 base64 = new Base64();
    byte tx[] = base64.decode(sign.getBytes("utf8"));

    byte[] tx_new = new byte[46];
    tx_new[0] = 48;
    tx_new[1] = 44;
    tx_new[2] = 2;
    tx_new[3] = 20;

    for (int x = 0; x < 20; x++) {
      tx_new[x + 4] = tx[x];
    }
    tx_new[24] = 2;
    tx_new[25] = 20;

    for (int x = 20; x < 40; x++) {
      tx_new[x + 6] = tx[x];
    }
    return tx_new;
  }
Exemplo n.º 11
0
  /**
   * 生成公匙和私匙
   *
   * @param seed 种子
   * @return
   * @throws Exception
   */
  public static Map<String, String> generateKey(String seed) throws Exception {
    Map<String, String> map = new HashMap<String, String>(2);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    Base64 base64 = new Base64();
    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    // BASE64Encoder encoder = new BASE64Encoder();
    // map.put("public", encoder.encode(publicKey.getEncoded()));
    // map.put("private", encoder.encode(privateKey.getEncoded()));
    map.put("public", publicKeyString);
    map.put("private", privateKeyString);

    System.out.println("publicKey: " + map.get("public"));
    System.out.println("privateKey: " + map.get("private"));
    return map;
  }
Exemplo n.º 12
0
  /**
   * 生成DSA运算需要的独立的p,q,g,j,x,y几个值
   *
   * @param seed 生成因子
   * @throws Exception
   * @author huangbuji
   *     <p>Create at 2014-2-8 下午4:45:26
   */
  @SuppressWarnings("restriction")
  public static void genKey(String seed) throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic();
    DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate();
    DSAParams dsaParams = privateKey.getParams();
    Base64 base64 = new Base64();
    String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8");
    String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8");
    String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8");
    String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8");
    String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8");
    System.out.println("P: " + p);
    System.out.println("Q: " + q);
    System.out.println("G: " + g);
    System.out.println("X: " + x);
    System.out.println("Y: " + y);

    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    System.err.println("public: " + publicKeyString);
    System.err.println("private: " + privateKeyString);

    File publicFile = new File("D:/binPublic.ky");
    File privateFile = new File("D:/binPrivate.ky");
    FileOutputStream out = new FileOutputStream(publicFile);
    out.write(publicKey.getEncoded());
    out.flush();
    out.close();
    out = new FileOutputStream(privateFile);
    out.write(privateKey.getEncoded());
    out.flush();
    out.close();
  }
 private Map<String, String> getAsMap() throws IOException, XPathExpressionException {
   InputStream zipInputStream =
       new ZipInputStream(new ByteArrayInputStream(Base64.decodeBase64(encodedZip)));
   ZipEntry zipFileEntry;
   Map<String, String> map = new HashMap<>();
   while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) {
     if (!zipFileEntry.getName().endsWith("-site.xml")) {
       continue;
     }
     byte[] bytes = IOUtils.toByteArray(zipInputStream);
     InputSource is = new InputSource(new ByteArrayInputStream(bytes));
     XPath xPath = XPathFactory.newInstance().newXPath();
     NodeList nodeList =
         (NodeList)
             xPath.evaluate(ConfigConstants.CONF_PROPERTY_XPATH, is, XPathConstants.NODESET);
     for (int i = 0; i < nodeList.getLength(); i++) {
       Node propNode = nodeList.item(i);
       String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING);
       String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING);
       map.put(key, value);
     }
   }
   return map;
 }
Exemplo n.º 14
0
 /**
  * 解密数据
  *
  * @param data 待解密数据
  * @param key 密钥
  * @return 解密后的数据
  */
 public static String decrypt(String data, String key) throws Exception {
   Key k = toKey(Base64.decodeBase64(key));
   Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
   cipher.init(Cipher.DECRYPT_MODE, k); // 初始化Cipher对象,设置为解密模式
   return new String(cipher.doFinal(Base64.decodeBase64(data))); // 执行解密操作
 }
Exemplo n.º 15
0
 /**
  * Encode a byte[] identifier as a Base64-encoded string.
  *
  * @param identifier identifier to encode
  * @return Base64-encoded string
  */
 static String encodeIdentifier(byte[] identifier) {
   return new String(Base64.encodeBase64(identifier), Charset.defaultCharset());
 }
Exemplo n.º 16
0
 public static String codificarUrl(String url) {
   return Base64.encodeBase64URLSafeString(url.getBytes());
 }
Exemplo n.º 17
0
 public static String decodificarUrl(String urlCoded) {
   return new String(Base64.decodeBase64(urlCoded.getBytes()));
 }
Exemplo n.º 18
0
 /**
  * Encode a byte[] identifier as a Base64-encoded string.
  *
  * @param identifier identifier to encode
  * @return Base64-encoded string
  */
 static String encodeIdentifier(byte[] identifier) {
   return new String(Base64.encodeBase64(identifier));
 }
Exemplo n.º 19
0
 public static SymmetricSecretKey valueOf(String key) {
   return decode(Base64.decodeBase64(key));
 }
Exemplo n.º 20
0
 @Override
 public String toString() {
   return Base64.encodeBase64String(encode());
 }
Exemplo n.º 21
0
 /**
  * Encode a password as a base64-encoded char[] array.
  *
  * @param password as a byte array.
  * @return password as a char array.
  */
 static char[] encodePassword(byte[] password) {
   return new String(Base64.encodeBase64(password)).toCharArray();
 }
Exemplo n.º 22
0
 public static String decrypt(String value) {
   if (!value.isEmpty()) {
     return new String(Base64.decodeBase64(value));
   }
   return value;
 }
Exemplo n.º 23
0
 /** 生成密钥 */
 public static String initkey() throws Exception {
   KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); // 实例化密钥生成器
   kg.init(128); // 初始化密钥生成器:AES要求密钥长度为128,192,256位
   SecretKey secretKey = kg.generateKey(); // 生成密钥
   return Base64.encodeBase64String(secretKey.getEncoded()); // 获取二进制密钥编码形式
 }