Пример #1
0
 @Test
 public void testSHA1() {
   eq(Crypto.sha1("abc"), "a9993e364706816aba3e25717850c26c9cd0d89d");
   eq(Crypto.sha1("x"), "11f6ad8ec52a2984abaafd7c3b516503785c2072");
   eq(Crypto.sha1(" "), "b858cb282617fb0956d960215c8e84d1ccf909c6");
   eq(Crypto.sha1(""), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
 }
Пример #2
0
 @Test
 public void testMD5() {
   eq(Crypto.md5("abc"), "900150983cd24fb0d6963f7d28e17f72");
   eq(Crypto.md5("x"), "9dd4e461268c8034f5c8564e155c67a6");
   eq(Crypto.md5(" "), "7215ee9c7d9dc229d2921a40e899ec5f");
   eq(Crypto.md5(""), "d41d8cd98f00b204e9800998ecf8427e");
 }
Пример #3
0
 @Test
 public void testEncrypt() {
   for (int i = 0; i < 10000; i++) {
     String msg1 = U.copyNtimes("x", i);
     byte[] enc = Crypto.encrypt(msg1.getBytes());
     byte[] dec = Crypto.decrypt(enc);
     String msg2 = new String(dec);
     eq(msg2, msg1);
   }
 }
Пример #4
0
  @Test
  public void testSecret() {
    notNull(Crypto.secret());
    isTrue(Crypto.secret() == Crypto.secret());

    // default secret in dev mode is an empty string
    eq(Crypto.secret(), "");

    Conf.args("secret=mysecret");
    eq(Crypto.secret(), "mysecret");
  }
Пример #5
0
  @Override
  public void execute() throws IOException {
    BufferedInputStream urlIn = new BufferedInputStream(new URL(url).openStream());
    File file = new File(filename);

    if ("".equals(aesKeyBase64)) {
      crypto.copyToFileClosing(urlIn, file);
    } else {
      crypto.decodeToFileClosing(aesKeyBase64, urlIn, file);
    }

    syserr("downloaded " + url + " to " + file);
  }
Пример #6
0
 @Test
 public void testSHA512() {
   eq(
       Crypto.sha512("abc"),
       "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
   eq(
       Crypto.sha512("x"),
       "a4abd4448c49562d828115d13a1fccea927f52b4d5459297f8b43e42da89238bc13626e43dcb38ddb082488927ec904fb42057443983e88585179d50551afe62");
   eq(
       Crypto.sha512(" "),
       "f90ddd77e400dfe6a3fcf479b00b1ee29e7015c5bb8cd70f5f15b4886cc339275ff553fc8a053f8ddc7324f45168cffaf81f8c3ac93996f6536eef38e5e40768");
   eq(
       Crypto.sha512(""),
       "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
 }
Пример #7
0
  /** Send session key to Bryan. */
  public void sendSessionKey() {

    SealedObject object = crypto.getSessionKey();
    try {
      this.toBryan.writeObject(object);
    } catch (IOException e) {
      System.out.println("Error: cannot send to Bryan.");
    }
  }
Пример #8
0
  @Override
  public void execute() throws IOException {
    File plainFile = new File(filename);
    File encodedFile = new File(filename2);

    crypto.encodeFile(aesKeyBase64, plainFile, encodedFile);

    syserr("encoded " + plainFile + " to " + encodedFile);
  }
  public void setMacName(String macName) {
    this.macName = macName;

    try {
      this.mac = Mac.getInstance(this.macName, Crypto.getCryptoProvider());
    } catch (GeneralSecurityException e) {
      throw new IllegalArgumentException(e);
    }
  }
Пример #10
0
 /** Wraps the input stream if it needs to be decrypted. */
 InputStream decrypt(InputStream in) throws IOException {
   if (mCrypto != null) {
     try {
       in = mCrypto.newDecryptingStream(0, in);
     } catch (GeneralSecurityException e) {
       throw new DatabaseException(e);
     }
   }
   return in;
 }
Пример #11
0
 /** Wraps the output stream if it needs to be encrypted. */
 OutputStream encrypt(OutputStream out) throws IOException {
   if (mCrypto != null) {
     try {
       out = mCrypto.newEncryptingStream(0, out);
     } catch (GeneralSecurityException e) {
       throw new DatabaseException(e);
     }
   }
   return out;
 }
Пример #12
0
  private String encrypt(String post) throws Exception {
    String code = "" + System.currentTimeMillis() + (new Random().nextInt(260000));
    String md5content = post + HSKEY_2 + code;
    String md5String = MD5.hexdigest(md5content);
    String hs = md5String.substring(0, 16);
    String key = hs + AUTHKEY_2;

    String aescontent = md5String.substring(16);
    String es = Crypto.encrypt(key, aescontent);
    String pj = "&token=" + es + "&code=" + code;
    return pj;
  }
Пример #13
0
  /*
   * creates a new packet valid for authentication an SIP request
   * @param answer  answer from server
   * @in: sendData - last send data
   * @out: new string
   */
  private String handleAuthentication(String answer, String sendData) {
    Crypto myCrypto = new Crypto(m_verbose);

    // increase cseq by one
    sendData = setCSeq(sendData, m_cseq + 1);

    String response =
        myCrypto.createResponse(
            m_userName,
            m_password,
            getAlg(answer),
            getRealm(answer),
            getNonce(answer),
            getSipMode(sendData.toUpperCase()),
            getOpaque(answer),
            "sip:tel.t-online.de");

    // TODO generic fix for authentication fix

    // insert reponse before "Content-Length"
    return insertText(sendData, response, "Content-Length");
  } // handleRegisterAuthentication
Пример #14
0
  /**
   * If the device has not previously generated and persisted its device ID (aka public/private
   * keypair for PSI), generates and stores said ID.
   *
   * <p>If the ID is already stored, this harmlessly does nothing.
   */
  private void generateAndStoreDeviceID(Context context, int encryption) {
    if (store == null) store = new StorageBase(context, encryption);
    String privateDeviceID = store.get(DEVICE_PRIVATE_ID_KEY);
    String publicDeviceID = store.get(DEVICE_PUBLIC_ID_KEY);
    if (privateDeviceID == null || publicDeviceID == null) {
      // This would be very strange, if only half the ID was stored.
      if (privateDeviceID != publicDeviceID) {
        if (privateDeviceID == null) {
          log.error(
              "Only one of private and public ID are stored! Public is stored, private is null.");
        } else {
          log.error(
              "Only one of private and public ID are stored! Private is stored, public is null.");
        }
      }

      AsymmetricCipherKeyPair keypair = Crypto.generateUserID();
      privateDeviceID = bytesToBase64(Crypto.generatePrivateID(keypair));
      publicDeviceID = bytesToBase64(Crypto.generatePublicID(keypair));

      store.put(DEVICE_PRIVATE_ID_KEY, privateDeviceID);
      store.put(DEVICE_PUBLIC_ID_KEY, publicDeviceID);
    }
  }
  public static void main(String[] args) {
    Options options = KeyGenCLI.buildOptions();
    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser parser = new GnuParser();

    try {
      CommandLine commandLine = parser.parse(options, args);
      String service = commandLine.getOptionValue("service");
      String key = Crypto.generateAes128KeyWithSeed(service);

      if (key == null) {
        throw new Exception("Key was not generated!");
      }

      JSONObject keyObject = new JSONObject();
      keyObject.put("name", service);
      keyObject.put("data", key);

      System.out.println(String.format("Key: `%s`\n", key));

      System.out.println("Key object:");
      System.out.println(keyObject.toString());
    } catch (MissingOptionException e) {
      System.out.println("Missing required option(s)!");
      helpFormatter.printHelp(
          "\nKeyGenCLI",
          "This tool generates a unique key and prints the result.",
          options,
          "",
          true);
    } catch (UnrecognizedOptionException e) {
      System.out.println("Unrecognized option!");
      helpFormatter.printHelp(
          "\nKeyGenCLI",
          "This tool generates a unique key and prints the result.",
          options,
          "",
          true);
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void setCipherAlgorithmNameModePadding(String cipherAlgorithmNameModePadding) {
    String cipherAlgorithmExpected, cipherAlgorithmReceived;

    cipherAlgorithmExpected = this.getCipherAlgorithm();
    cipherAlgorithmReceived = CryptoUtil.getCipherNameAsString(cipherAlgorithmNameModePadding);

    if (!cipherAlgorithmExpected.equals(cipherAlgorithmReceived)) {
      throw new IllegalArgumentException("algorithm must be " + cipherAlgorithmExpected);
    }

    this.cipherAlgorithmNameModePadding = cipherAlgorithmNameModePadding;

    try {
      this.cipher =
          Cipher.getInstance(this.cipherAlgorithmNameModePadding, Crypto.getCryptoProvider());
    } catch (GeneralSecurityException e) {
      logException(getClass(), e);
      throw new IllegalArgumentException(e);
    }
  }
Пример #17
0
  /** Receive messages one by one from Bryan, decrypt and write to file */
  public void receiveMessages() {

    try {
      PrintWriter writer = new PrintWriter(new FileWriter(MESSAGE_FILE));

      for (int i = 0; i < 10; i++) {
        SealedObject object = (SealedObject) this.fromBryan.readObject();
        String msg = crypto.decryptMsg(object);
        writer.write(msg);
        writer.write("\n");
      }
      writer.close();
    } catch (ClassNotFoundException e) {
      System.out.println("Error: cannot typecast to class SealedObject.");
      System.exit(1);
    } catch (IOException e) {
      System.out.println("Error: cannot receive messages from Bryan.");
      System.exit(1);
    }
  }
Пример #18
0
  /** Receive public key from Bryan */
  public void receivePublicKey() {

    try {
      PublicKey pubKey = (PublicKey) this.fromBryan.readObject();
      byte[] digest = (byte[]) this.fromBryan.readObject();

      boolean isVerified = crypto.verifyBryanPubKey(pubKey, digest);

      if (!isVerified) {
        System.out.println("Error:MD5 signature does not match");
        System.exit(1);
      }

    } catch (ClassNotFoundException e) {
      System.out.println("Error: cannot typecast to class PublicKey or byte[].");
      System.exit(1);
    } catch (IOException e) {
      System.out.println("Error: cannot varify bryan's key.");
      System.exit(1);
    }
  }
Пример #19
0
 @Test
 public void testDigest() {
   notNull(Crypto.digest("MD5"));
   notNull(Crypto.digest("SHA-1"));
   notNull(Crypto.digest("SHA-512"));
 }
Пример #20
0
  public static boolean backUp(Context context, backUpCall back) {
    int process = 0;
    // 判断当前sd卡的状态
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      Log.v("Daniel", "有sd卡");
      ContentResolver resolver = context.getContentResolver();
      // 拿到获取短信的uri
      Uri uri = Uri.parse("content://sms/");
      /*
       * type=1,表示接受的短信 type=2,表示发送的短信
       */
      Cursor cursor =
          resolver.query(uri, new String[] {"address", "date", "type", "body"}, null, null, null);

      int count = cursor.getCount();
      back.before(count);
      XmlSerializer serializer = Xml.newSerializer();
      // 在sd卡创建backup.xml的文件
      File file = new File(Environment.getExternalStorageDirectory(), "backup.xml");
      Log.v("Daniel", "创建好了文件");
      try {
        FileOutputStream os = new FileOutputStream(file);
        // serilizer的输出位置就是os
        serializer.setOutput(os, "UTF-8");
        // 设置编码格式,以及独立存在
        serializer.startDocument("utf-8", true);
        // 开始节点为“smss”
        serializer.startTag(null, "smss");
        // 开始节点为address
        while (cursor.moveToNext()) {
          serializer.startTag(null, "address");
          serializer.text(cursor.getString(0));
          serializer.endTag(null, "address");
          // 开始节点为data
          serializer.startTag(null, "data");
          serializer.text(cursor.getString(1));
          serializer.endTag(null, "data");
          // 开始节点为type
          serializer.startTag(null, "type");
          serializer.text(cursor.getString(2));
          serializer.endTag(null, "type");
          // 开始节点为body
          serializer.startTag(null, "body");
          serializer.text(Crypto.encrypt("231617", cursor.getString(3)));
          serializer.endTag(null, "body");
          SystemClock.sleep(1000);
          process++;
          back.onBackUp(process);
        }
        serializer.endTag(null, "smss");
        serializer.endDocument();

        cursor.close();
        os.flush();
        os.close();
        return true;
      } catch (Exception e) {
        // TODO Auto-generated catch block
      }
    }
    return false;
  }
        @Override
        public void onClick(View view) {

          Utils.Log("Send clicked");

          // If the message field is not empty
          if (!messageText.getText().toString().isEmpty()) {

            final Message message = new Message();
            message.setSender(username);
            message.setRecipient(conversation.getUsername());

            // If DHKE was completed and a key exists
            if (!dbManager.getAESKey(conversation.getUsername()).isEmpty()) {
              String signature = "";
              String key = dbManager.getAESKey(conversation.getUsername());
              byte[] iv = Crypto.GenerateRandomIV();
              final String plainText = messageText.getText().toString();
              final String cipherText = Crypto.AESencrypt(key, plainText, iv);
              final String base64IV = Base64.encodeToString(iv, Base64.NO_WRAP);

              try {
                PrivateKey RSAKeySign =
                    Crypto.RSAStringToPrivateKey(dbManager.getRSAKeySignaturePrivate());

                signature =
                    Base64.encodeToString(
                        Crypto.RSASign(Base64.decode(cipherText, Base64.NO_WRAP), RSAKeySign),
                        Base64.NO_WRAP);

              } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
              } catch (InvalidKeySpecException e) {
                e.printStackTrace();
              } catch (NoSuchProviderException e) {
                e.printStackTrace();
              } catch (InvalidKeyException e) {
                e.printStackTrace();
              } catch (SignatureException e) {
                e.printStackTrace();
              }

              message.setMessage(cipherText);
              message.setIv(base64IV);
              message.setSignature(signature);

              new HttpHandler() {
                @Override
                public HttpUriRequest getHttpRequestMethod() {
                  HttpPost httpPost = new HttpPost(Utils.SERVER_SEND_MESSAGE);

                  List<NameValuePair> nameValuePairs = new ArrayList<>();
                  nameValuePairs.add(new BasicNameValuePair("sender", message.getSender()));
                  nameValuePairs.add(new BasicNameValuePair("recipient", message.getRecipient()));
                  nameValuePairs.add(new BasicNameValuePair("message", message.getMessage()));
                  nameValuePairs.add(new BasicNameValuePair("iv", message.getIv()));
                  nameValuePairs.add(new BasicNameValuePair("signature", message.getSignature()));

                  try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                  } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                  }

                  return httpPost;
                }

                @Override
                public void onResponse(String result) {
                  Utils.Log("HttpResult: " + result);

                  if (conversation.isEncrypted().equals("true")) {
                    message.setMessage(
                        Crypto.AESencrypt(
                            conversationPass,
                            plainText,
                            Base64.decode(message.getIv(), Base64.NO_WRAP)));
                    message.setEncrypted(true);

                    dbManager.addMessage(message);

                    message.setEncrypted(false);
                    message.setMessage(plainText);

                    messages.add(message);
                    adapter.notifyDataSetChanged();

                  } else {
                    message.setMessage(plainText);
                    message.setEncrypted(false);

                    dbManager.addMessage(message);

                    messages.add(message);
                    adapter.notifyDataSetChanged();
                  }

                  messageList.setSelection(messages.size() + 1);
                }
              }.execute();

              messageText.setText("");

            }

            // DHKE was not complete yet, store messages unencrypted temporarily
            // and then encrypt and send them once the exchange is complete
            else {
              message.setEncrypted(false);
              message.setMessage(messageText.getText().toString());
              message.setIv(Base64.encodeToString(Crypto.GenerateRandomIV(), Base64.NO_WRAP));

              dbManager.addMessage(message);

              messages.add(message);
              adapter.notifyDataSetChanged();

              messageList.setSelection(adapter.getCount() - 1);
              messageText.setText("");
            }
          }
        }