Пример #1
0
 public byte[] readPrivateKeyToPKCSBytes(char[] encpass, String salt, String iv, String keyData)
     throws GeneralSecurityException {
   Key key = getKeyDecryptionKey(encpass, Base64.decode(salt));
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME);
   cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Base64.decode(iv)));
   return cipher.doFinal(Base64.decode(keyData));
 }
Пример #2
0
 public byte[] decrypt(Key secKey, String ciphertext, String iv, String hmac)
     throws GeneralSecurityException {
   // checkMac(secKey, ciphertext, hmac);
   byte[] ciphertextbytes = Base64.decode(ciphertext);
   byte[] ivBytes = Base64.decode(iv);
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME);
   cipher.init(Cipher.DECRYPT_MODE, secKey, new IvParameterSpec(ivBytes));
   return cipher.doFinal(ciphertextbytes);
 }
Пример #3
0
 public Key unwrapSecretKey(RSAPrivateKey privKey, String wrapped)
     throws GeneralSecurityException {
   byte[] wrappedBytes = Base64.decode(wrapped);
   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER_NAME);
   cipher.init(Cipher.UNWRAP_MODE, privKey);
   return cipher.unwrap(wrappedBytes, "AES", Cipher.SECRET_KEY);
 }
Пример #4
0
  /**
   * @param s
   * @return
   * @throws GeneralSecurityException
   * @throws UnsupportedEncodingException
   */
  public static String decrypt(final String s)
      throws GeneralSecurityException, UnsupportedEncodingException {
    String decrypted = null;

    try {
      if (s != null) {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey secretKey =
            secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray()));
        final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20));
        final byte[] stringBytes = s.getBytes("UTF-8");
        final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        decrypted = new String(decryptedBytes, "UTF-8");
      }
    } catch (GeneralSecurityException x) {
      throw x;
    } catch (UnsupportedEncodingException x) {
      throw x;
    } catch (Exception x) {
      DBG.m(x);
    }

    return decrypted;
  }
Пример #5
0
  private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
    String user;
    String password;
    if (userInfo != null) { // get the user and password
      // System.out.println("UserInfo= " + userInfo );
      int delimiter = userInfo.indexOf(':');
      if (delimiter == -1) {
        user = ParseUtil.decode(userInfo);
        password = null;
      } else {
        user = ParseUtil.decode(userInfo.substring(0, delimiter++));
        password = ParseUtil.decode(userInfo.substring(delimiter));
      }

      String plain = user + ":";
      byte[] nameBytes = plain.getBytes();
      byte[] passwdBytes = password.getBytes();

      // concatenate user name and password bytes and encode them
      byte[] concat = new byte[nameBytes.length + passwdBytes.length];

      System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
      System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length);
      String auth = "Basic " + new String(Base64.encode(concat));
      conn.setRequestProperty("Authorization", auth);
      if (dL > 0) d("Adding auth " + auth);
    }
  }
Пример #6
0
 public RSAPublicKey readCertificatePubKey(String base64EncodedCert)
     throws GeneralSecurityException {
   byte[] certBytes = Base64.decode(base64EncodedCert);
   // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(certBytes);
   // KeyFactory certFact = KeyFactory.getInstance("RSA", PROVIDER_NAME);
   // return (RSAPublicKey)certFact.generatePublic(keySpec);
   return (RSAPublicKey) readCertificate(certBytes);
 }
 /**
  * Converts a PEM-encoded PKCS#8 private key into an RSAPrivateKey instance useable with JCE
  *
  * @param privateKey private key in PKCS#8 format and PEM-encoded
  * @return RSAPrivateKey instance containing the key
  */
 private static RSAPrivateKey rsaPrivateKeyDecode(final String privateKey) {
   try {
     final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
     final KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodePadded(privateKey));
     return (RSAPrivateKey) keyFactory.generatePrivate(ks);
   } catch (final Exception e) {
     throw new RuntimeException("Failed to decode built-in private key", e);
   }
 }
Пример #8
0
  public String verify(JarFile jar, String... algorithms) throws IOException {
    if (algorithms == null || algorithms.length == 0) algorithms = new String[] {"MD5", "SHA"};
    else if (algorithms.length == 1 && algorithms[0].equals("-")) return null;

    try {
      Manifest m = jar.getManifest();
      if (m.getEntries().isEmpty()) return "No name sections";

      for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
        JarEntry je = e.nextElement();
        if (MANIFEST_ENTRY.matcher(je.getName()).matches()) continue;

        Attributes nameSection = m.getAttributes(je.getName());
        if (nameSection == null) return "No name section for " + je.getName();

        for (String algorithm : algorithms) {
          try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            String expected = nameSection.getValue(algorithm + "-Digest");
            if (expected != null) {
              byte digest[] = Base64.decodeBase64(expected);
              copy(jar.getInputStream(je), md);
              if (!Arrays.equals(digest, md.digest()))
                return "Invalid digest for "
                    + je.getName()
                    + ", "
                    + expected
                    + " != "
                    + Base64.encodeBase64(md.digest());
            } else reporter.error("could not find digest for " + algorithm + "-Digest");
          } catch (NoSuchAlgorithmException nsae) {
            return "Missing digest algorithm " + algorithm;
          }
        }
      }
    } catch (Exception e) {
      return "Failed to verify due to exception: " + e.getMessage();
    }
    return null;
  }
Пример #9
0
  public static void main(String[] args) {
    String pubKey =
        "30819f300d06092a864886f70d010101050003818d0030818902818100aead2fa0c97106c8dc4a72ed496b42fab8deff4c130d430fc382272f7ed1315ebbacd734cf2f98d27bf7ce8c0aacb0ee763e56b4525ba020081acd89ff1cb8c45afb604a3b2a8bae51fb815b0bde4144e291d6a86c028db16f6e4467f01bf78921c656014ed01f485713f5d2173faae6996db04a59c83924b12e995f8fb2388d0203010001";

    String pKey =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCurS+gyXEGyNxKcu1Ja0L6uN7/TBMNQw/DgicvftExXrus1zTPL5jSe/fOjAqssO52Pla0UlugIAgazYn/HLjEWvtgSjsqi65R+4FbC95BROKR1qhsAo2xb25EZ/Ab94khxlYBTtAfSFcT9dIXP6rmmW2wSlnIOSSxLplfj7I4jQIDAQAB";
    System.out.println(bytesToHexStr(Base64.decode(pKey)));

    EsalesRAS ras = new EsalesRAS();
    String sign_org =
        "993991d16da5eef7576ec6052a336a0c5a886287af63800ced020f4b9faf680f07ac8fd441cfc050f78ee785b046a350bd05217dcc88da74390129a7df0cbdd0469ca97417cf172f94a54532288e7fff8a1ccebeefbc5e5d2fc477fda7de28b554b4d2fda907abcd87b624afa438933dfa52e7fe5b54e4a38bb6a40b94e2b9e6";
    String source = "ARG_ERRsign289632";
    System.out.println(ras.verifySHA1withRSASigature(sign_org, source, pubKey));
  }
Пример #10
0
 /**
  * Generates a PublicKey instance from a string containing the Base64-encoded public key.
  *
  * @param encodedPublicKey Base64-encoded public key
  * @throws IllegalArgumentException if encodedPublicKey is invalid
  */
 private PublicKey generatePublicKey(String encodedPublicKey) {
   try {
     byte[] decodedKey = Base64.decode(encodedPublicKey);
     KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
     return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   } catch (InvalidKeySpecException e) {
     Log.e(TAG, "Invalid key specification.");
     throw new IllegalArgumentException(e);
   } catch (Base64DecoderException e) {
     Log.e(TAG, "Base64 decoding failed.");
     throw new IllegalArgumentException(e);
   }
 }
Пример #11
0
 /**
  * Verifies that the signature from the server matches the computed signature on the data.
  * Returns true if the data is correctly signed.
  *
  * @param signedData signed data from server
  * @param signature server signature
  * @return true if the data and signature match
  */
 private boolean verify(String signedData, String signature) {
   Signature sig;
   try {
     sig = Signature.getInstance(SIGNATURE_ALGORITHM);
     sig.initVerify(key);
     sig.update(signedData.getBytes());
     if (!sig.verify(Base64.decode(signature))) {
       Log.e(TAG, "Signature verification failed.");
       return false;
     }
     return true;
   } catch (NoSuchAlgorithmException e) {
     Log.e(TAG, "NoSuchAlgorithmException.");
   } catch (InvalidKeyException e) {
     Log.e(TAG, "Invalid key specification.");
   } catch (SignatureException e) {
     Log.e(TAG, "Signature exception.");
   } catch (Base64DecoderException e) {
     Log.e(TAG, "Base64 decoding failed.");
   }
   return false;
 }
Пример #12
0
 @SuppressWarnings("unused")
 private byte[] encrypt(Key secKey, String plaintext, String iv) throws GeneralSecurityException {
   byte[] plaintextbytes = Base64.decode(plaintext);
   return encrypt(secKey, plaintextbytes, iv);
 }
Пример #13
0
 private byte[] encrypt(Key secKey, byte[] plaintext, String iv) throws GeneralSecurityException {
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME);
   cipher.init(Cipher.ENCRYPT_MODE, secKey, new IvParameterSpec(Base64.decode(iv)));
   return cipher.doFinal(plaintext);
 }