Ejemplo n.º 1
0
  public static String decryptIt(String value) {
    try {
      DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey key = keyFactory.generateSecret(keySpec);

      byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
      // cipher is not thread safe
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

      String decrypedValue = new String(decrypedValueBytes);
      Log.d(TAG, "Decrypted: " + value + " -> " + decrypedValue);
      return decrypedValue;

    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    }
    return value;
  }
Ejemplo n.º 2
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
      RSACryptoProvider rsa = new RSACryptoProvider();
      byte[] data = rsa.Encrypt("Michael");
      System.out.println(new String(data));
      System.out.println(rsa.Decrypt(data));

    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (BadPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  /**
   * Returns the key pair (private and public key) for the local machine
   *
   * @param sessionID sessionID for currect machine
   */
  public KeyPair loadLocalKeyPair(SessionID sessionID) {
    if (sessionID == null) return null;

    String accountID = sessionID.getAccountID();
    // Load Private Key.
    byte[] b64PrivKey = this.store.getPropertyBytes(accountID + ".privateKey");
    if (b64PrivKey == null) return null;

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey);

    // Load Public Key.
    byte[] b64PubKey = this.store.getPropertyBytes(accountID + ".publicKey");
    if (b64PubKey == null) return null;

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);

    PublicKey publicKey;
    PrivateKey privateKey;

    // Generate KeyPair.
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance("DSA");
      publicKey = keyFactory.generatePublic(publicKeySpec);
      privateKey = keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }

    return new KeyPair(publicKey, privateKey);
  }
Ejemplo n.º 4
0
  /**
   * 生成公钥
   *
   * @param modulus
   * @param publicExponent
   * @return RSAPublicKey
   * @throws Exception
   */
  public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent)
      throws Exception {

    KeyFactory keyFac = null;

    try {

      keyFac =
          KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

    } catch (NoSuchAlgorithmException ex) {

      throw new Exception(ex.getMessage());
    }

    RSAPublicKeySpec pubKeySpec =
        new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));

    try {

      return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);

    } catch (InvalidKeySpecException ex) {

      throw new Exception(ex.getMessage());
    }
  }
  private PublicKey loadRemotePublicKeyFromStore(String fullUserId) {

    //  if (!Address.hasResource(fullUserId))
    //    return null;

    byte[] b64PubKey = this.store.getPropertyBytes(fullUserId + ".publicKey");
    if (b64PubKey == null) {
      return null;
    }

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);

    // Generate KeyPair from spec
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance(KEY_ALG);

      return keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }
  }
  private KeyPair loadLocalKeyPair(String fullUserId) {
    PublicKey publicKey;
    PrivateKey privateKey;

    String userId = Address.stripResource(fullUserId);

    try {
      // Load Private Key.

      byte[] b64PrivKey = this.store.getPropertyBytes(userId + ".privateKey");
      if (b64PrivKey == null) return null;

      PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey);

      // Generate KeyPair.
      KeyFactory keyFactory;
      keyFactory = KeyFactory.getInstance(KEY_ALG);
      privateKey = keyFactory.generatePrivate(privateKeySpec);

      // Load Public Key.
      byte[] b64PubKey = this.store.getPropertyBytes(userId + ".publicKey");
      if (b64PubKey == null) return null;

      X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);
      publicKey = keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }

    return new KeyPair(publicKey, privateKey);
  }
  public Key getDesEncryptionKey() throws PropertyManagerException {
    try {
      // get the key string
      String keyStr = getPropertyObject(DES_ENCRYPTION_KEY).getValue();

      // create a DES key spec
      DESKeySpec ks = new DESKeySpec(new sun.misc.BASE64Decoder().decodeBuffer(keyStr));

      // generate the key from the DES key spec
      return SecretKeyFactory.getInstance(DESPasswordEncoder.PASSWORD_ENCRYPTION_ALGORITHM)
          .generateSecret(ks);

    } catch (NoSuchAlgorithmException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (IOException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (ObjectNotFoundException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (InvalidKeyException e) {
      throw new PropertyManagerException(e.getMessage(), e);

    } catch (InvalidKeySpecException e) {
      throw new PropertyManagerException(e.getMessage(), e);
    }
  }
Ejemplo n.º 8
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException {
    byte[] encoded = null;
    try {
      encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
Ejemplo n.º 9
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] encoded;
    try {
      if (wrapEngine == null) {
        encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
      } else {
        encoded = wrapEngine.unwrap(wrappedKey, 0, wrappedKey.length);
      }
    } catch (InvalidCipherTextException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else if (wrappedKeyAlgorithm.equals("") && wrappedKeyType == Cipher.PRIVATE_KEY) {
      /*
       * The caller doesn't know the algorithm as it is part of
       * the encrypted data.
       */
      try {
        PrivateKeyInfo in = PrivateKeyInfo.getInstance(encoded);

        PrivateKey privKey = BouncyCastleProvider.getPrivateKey(in);

        if (privKey != null) {
          return privKey;
        } else {
          throw new InvalidKeyException(
              "algorithm " + in.getPrivateKeyAlgorithm().getAlgorithm() + " not supported");
        }
      } catch (Exception e) {
        throw new InvalidKeyException("Invalid key encoding.");
      }
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
 public void rsaCypher(String rString, InputStream inputStream, File directory)
     throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException,
         BadPaddingException, IllegalBlockSizeException {
   kpg = KeyPairGenerator.getInstance("RSA");
   kpg.initialize(1024);
   kp = kpg.genKeyPair();
   privateKey = kp.getPrivate();
   cipher = Cipher.getInstance("RSA");
   File root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsapublick.txt");
   // Read text from file
   if (root.exists()) {
     StringBuilder text = new StringBuilder();
     try {
       BufferedReader br = new BufferedReader(new FileReader(root));
       String line;
       while ((line = br.readLine()) != null) {
         text.append(line);
         text.append('\n');
       }
       br.close();
       byte[] keyBytes = Base64.decode(text.toString().getBytes("utf-8"), 0);
       X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
       KeyFactory keyFactory = KeyFactory.getInstance("RSA");
       publicKey = keyFactory.generatePublic(spec);
     } catch (IOException e) {
       // You'll need to add proper error handling here
     } catch (InvalidKeySpecException e) {
       e.printStackTrace();
     }
   } else {
     publicKey = kp.getPublic();
     byte[] pKbytes = Base64.encode(publicKey.getEncoded(), 0);
     String pK = new String(pKbytes);
     String pubKey = "-----BEGIN public KEY-----\n" + pK + "-----END public KEY-----\n";
     System.out.println(pubKey);
     generateNoteOnSD("rsapublick.txt", pK, directorio);
   }
   this.cipher.init(Cipher.ENCRYPT_MODE, publicKey);
   byte[] bytes = getBytesFromInputStream(inputStream);
   byte[] encrypted = blockCipher(bytes, Cipher.ENCRYPT_MODE);
   FileOutputStream fileOutputStream = new FileOutputStream(directory);
   fileOutputStream.write(encrypted);
   fileOutputStream.close();
   System.out.println("Encryptado RSA Finalizado");
   root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsaOrivatek.txt");
   if (!root.exists()) {
     byte[] pKbytes = Base64.encode(getPrivateKey().getEncoded(), 0);
     String pK = new String(pKbytes);
     String pubKey = "-----BEGIN private KEY-----\n" + pK + "-----END private KEY-----\n";
     System.out.println(pubKey);
     generateNoteOnSD("rsaOrivatek.txt", pK, directorio);
   }
 }
Ejemplo n.º 11
0
  public static byte[] passwordEncrypt(char[] password, byte[] plaintext) {
    byte[] salt = new byte[8];
    Random random = new Random();
    random.nextBytes(salt);

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = null;
    try {
      keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey key = null;
    try {
      key = keyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    }
    try {
      cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }

    byte[] ciphertext = new byte[0];
    try {
      ciphertext = cipher.doFinal(plaintext);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      baos.write(salt);
      baos.write(ciphertext);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return baos.toByteArray();
  }
Ejemplo n.º 12
0
 public static void test2() {
   try {
     String pass1 = PasswordHash.createHash("123");
     System.out.println(pass1);
     String s =
         "1000:7af36fc2d12dcf5b7104dfc47c1ac1fd6e7b12681bede0c5:bcbcab2c9f6689fb2f738e6fe98201089b65d99e037462c5";
     System.out.println(s.length());
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (InvalidKeySpecException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 13
0
 public static PublicKey func_75896_a(byte p_75896_0_[]) {
   try {
     X509EncodedKeySpec x509encodedkeyspec = new X509EncodedKeySpec(p_75896_0_);
     KeyFactory keyfactory = KeyFactory.getInstance("RSA");
     return keyfactory.generatePublic(x509encodedkeyspec);
   } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
     nosuchalgorithmexception.printStackTrace();
   } catch (InvalidKeySpecException invalidkeyspecexception) {
     invalidkeyspecexception.printStackTrace();
   }
   System.err.println("Public key reconstitute failed!");
   return null;
 }
Ejemplo n.º 14
0
  public static PublicKey func_75896_a(byte[] par0ArrayOfByte) {
    try {
      X509EncodedKeySpec var1 = new X509EncodedKeySpec(par0ArrayOfByte);
      KeyFactory var2 = KeyFactory.getInstance("RSA");
      return var2.generatePublic(var1);
    } catch (NoSuchAlgorithmException var3) {
      var3.printStackTrace();
    } catch (InvalidKeySpecException var4) {
      var4.printStackTrace();
    }

    System.err.println("Public key reconstitute failed!");
    return null;
  }
Ejemplo n.º 15
0
 public static String decrypt(String property) {
   SecretKeyFactory keyFactory = null;
   String retValue = null;
   try {
     keyFactory = SecretKeyFactory.getInstance(encrypteAlgorithm);
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   SecretKey key = null;
   try {
     key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
   } catch (InvalidKeySpecException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   Cipher pbeCipher = null;
   try {
     pbeCipher = Cipher.getInstance(encrypteAlgorithm);
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   try {
     pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
   } catch (InvalidKeyException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (InvalidAlgorithmParameterException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   try {
     retValue = new String(pbeCipher.doFinal(base64Decode(property)));
   } catch (IllegalBlockSizeException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (BadPaddingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return retValue;
 }
Ejemplo n.º 16
0
  public static byte[] passwordDecrypt(char[] password, byte[] ciphertext) {
    byte[] salt = new byte[8];
    ByteArrayInputStream bais = new ByteArrayInputStream(ciphertext);
    bais.read(salt, 0, 8);

    byte[] remainingCiphertext = new byte[ciphertext.length - 8];
    bais.read(remainingCiphertext, 0, ciphertext.length - 8);

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = null;
    try {
      keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey secretKey = null;
    try {
      secretKey = keyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }

    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);

    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    }
    try {
      cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }

    try {
      return cipher.doFinal(remainingCiphertext);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 17
0
  /**
   * Loads the public key used for encrypting statistical data.
   *
   * @param file
   * @return
   */
  public PublicKey loadPublicKey(File file) {
    try {
      byte[] encodedPublicKey = loadBytesFromFile(file);

      return publicKeyFromBytes(encodedPublicKey);

    } catch (InvalidKeySpecException e) {
      throw new IllegalStateException(
          "Unable to create key from encoded specification in "
              + file.getAbsolutePath()
              + "; "
              + e.getMessage(),
          e);
    }
  }
Ejemplo n.º 18
0
 public static void test3() {
   try {
     String pwd = "123";
     String passHash1 = PasswordHash.createHash(pwd);
     String passHash2 = PasswordHash.createHash(pwd);
     boolean flag1 = PasswordHash.validatePassword(pwd, passHash1);
     boolean flag2 = PasswordHash.validatePassword(pwd, passHash2);
     System.out.println(flag1);
     System.out.println(flag2);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (InvalidKeySpecException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 19
0
 public PrivateKey readKey(String name) throws IOException {
   RSAPrivateCrtKeySpec sp = readKeyFile(name);
   KeyFactory kf;
   try {
     kf = KeyFactory.getInstance("RSA");
   } catch (NoSuchAlgorithmException e) {
     throw new IOException("RSA: " + e.toString());
   }
   PrivateKey pk;
   try {
     pk = kf.generatePrivate(sp);
   } catch (InvalidKeySpecException e) {
     throw new IOException(e.toString());
   }
   return pk;
 }
Ejemplo n.º 20
0
 /** @see org.apache.james.jdkim.api.PublicKeyRecord#getPublicKey() */
 public PublicKey getPublicKey() {
   try {
     String p = getValue("p").toString();
     byte[] key = Base64.decodeBase64(p.getBytes());
     KeyFactory keyFactory;
     keyFactory = KeyFactory.getInstance(getValue("k").toString());
     X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(key);
     RSAPublicKey rsaKey;
     rsaKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
     return rsaKey;
   } catch (NoSuchAlgorithmException e) {
     throw new IllegalStateException("Unknown algorithm: " + e.getMessage());
   } catch (InvalidKeySpecException e) {
     throw new IllegalStateException("Invalid key spec: " + e.getMessage());
   }
 }
Ejemplo n.º 21
0
 public void loadPrivateKey(String privateKeyStr) throws Exception {
   try {
     BASE64Decoder base64Decoder = new BASE64Decoder();
     byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
     PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
     KeyFactory keyFactory = KeyFactory.getInstance("RSA");
     this.privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
   } catch (NoSuchAlgorithmException e) {
     throw new Exception("无此算法");
   } catch (InvalidKeySpecException e) {
     e.printStackTrace();
     throw new Exception("私钥非法");
   } catch (IOException e) {
     throw new Exception("私钥数据内容读取错误");
   } catch (NullPointerException e) {
     throw new Exception("私钥数据为空");
   }
 }
Ejemplo n.º 22
0
  /**
   * 将公钥解码
   *
   * @param privKeyEncryped
   * @return
   */
  public PublicKey decodePublicKey(String encodedKey) {
    byte[] keyBytes = Base64.decode(encodedKey, Base64.DEFAULT);

    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = null;
    PublicKey publicKey = null;

    try {
      keyFactory = KeyFactory.getInstance(CIP_ALGO);
      publicKey = keyFactory.generatePublic(keySpec);

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }

    return publicKey;
  }
Ejemplo n.º 23
0
 public static Key password2Key(String password, SecretKeyFactory... factories) {
   if (Strings.isNullOrEmpty(password)) {
     if (pbeLog.isDebugEnabled()) {
       pbeLog.debug(
           "The given password is a empty(null), using default password {}", DEFAULT_PASSWORD);
     }
     password = DEFAULT_PASSWORD;
   }
   PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
   SecretKeyFactory skf = getDefaultKeyFactory();
   if (factories != null && factories.length > 0 && factories[0] != null) {
     skf = factories[0];
   }
   try {
     return skf.generateSecret(keySpec);
   } catch (InvalidKeySpecException ex) {
     pbeLog.warn("PBEKeySpec keySpec is error - " + ex.getMessage());
   }
   return null;
 }
Ejemplo n.º 24
0
 /**
  * Loads the public key from a byte array
  *
  * @param keyBytes the public key
  * @return if an error occures null will be returned
  */
 public static PublicKey loadPublicECDSAKey(byte[] keyBytes) {
   X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
   KeyFactory keyFactory;
   try {
     keyFactory = KeyFactory.getInstance("ECDSA", "SC");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     return null;
   } catch (NoSuchProviderException e) {
     e.printStackTrace();
     return null;
   }
   PublicKey key;
   try {
     key = keyFactory.generatePublic(spec);
   } catch (InvalidKeySpecException e) {
     e.printStackTrace();
     return null;
   }
   return key;
 }
Ejemplo n.º 25
0
  /**
   * 使用口令解密还原私钥
   *
   * @return
   */
  public PrivateKey decryptPrivateKey(String passphrase, String privKeyEncryped) {
    byte[] seeds = null;
    byte[] raw = Base64.decode(privKeyEncryped, Base64.DEFAULT);
    byte[] decrypted = null;

    try {
      seeds = getRawKey(passphrase.getBytes());

      SecretKeySpec skeySpec = new SecretKeySpec(seeds, PASS_ALGO);
      Cipher cipher = Cipher.getInstance(PASS_ALGO);
      cipher.init(Cipher.DECRYPT_MODE, skeySpec);
      decrypted = cipher.doFinal(raw);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decrypted);
    KeyFactory keyFactory = null;
    PrivateKey privateKey = null;

    try {
      keyFactory = KeyFactory.getInstance(CIP_ALGO);
      privateKey = keyFactory.generatePrivate(keySpec);

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }

    return privateKey;
  }
  /**
   * Given the remaining lines in a BIND9 style DSA private key, parse the key info and translate it
   * into a JCA private key.
   *
   * @throws NoSuchAlgorithmException if the DSA algorithm is not available.
   */
  private PrivateKey parsePrivateDSA(StringTokenizer lines) throws NoSuchAlgorithmException {
    BigInteger p = null;
    BigInteger q = null;
    BigInteger g = null;
    BigInteger x = null;

    while (lines.hasMoreTokens()) {
      String line = lines.nextToken();
      if (line == null) continue;

      if (line.startsWith("#")) continue;

      String val = value(line);
      if (val == null) continue;

      byte[] data = base64.fromString(val);

      if (line.startsWith("Prime(p): ")) {
        p = new BigInteger(1, data);
      } else if (line.startsWith("Subprime(q): ")) {
        q = new BigInteger(1, data);
      } else if (line.startsWith("Base(g): ")) {
        g = new BigInteger(1, data);
      } else if (line.startsWith("Private_value(x): ")) {
        x = new BigInteger(1, data);
      }
    }

    try {
      KeySpec spec = new DSAPrivateKeySpec(x, p, q, g);
      if (mDSAKeyFactory == null) {
        mDSAKeyFactory = KeyFactory.getInstance("DSA");
      }
      return mDSAKeyFactory.generatePrivate(spec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 27
0
  /**
   * Loads the public key for the specified sessionID. If there is no key stored, you will get
   * 'null'
   */
  public PublicKey loadRemotePublicKey(SessionID sessionID) {
    if (sessionID == null) return null;

    String userID = sessionID.getUserID();

    byte[] b64PubKey = this.store.getPropertyBytes(userID + ".publicKey");
    if (b64PubKey == null) return null;

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);

    // Generate KeyPair.
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance("DSA");
      return keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }
  }
  public boolean login() throws LoginException {
    System.out.println("Login Module - login called");
    if (callbackHandler == null) {
      throw new LoginException("Oops, callbackHandler is null");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("name:");
    callbacks[1] = new PasswordCallback("password:"******"Oops, IOException calling handle on callbackHandler");
    } catch (UnsupportedCallbackException e) {
      throw new LoginException(
          "Oops, UnsupportedCallbackException calling handle on callbackHandler");
    }

    NameCallback nameCallback = (NameCallback) callbacks[0];
    PasswordCallback passwordCallback = (PasswordCallback) callbacks[1];
    loggedUser = new User();
    loggedUser.setUsername(nameCallback.getName());
    loggedUser.setPassword(String.valueOf(passwordCallback.getPassword()));

    MyDatabase database = null;
    try {
      database = new MyDatabase(options);
      database.createDatabaseConnection();
      if (database.loginUser(loggedUser.getUsername(), loggedUser.getPassword())) {

        loggedUser.setRole(database.getUserRole(loggedUser));
        System.out.println("Il database ha tornato il valore");
        succeeded = true;
      } else {
        System.out.println("Il database non ha tornato il valore");

        succeeded = false;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return succeeded;
  }
        @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("");
            }
          }
        }
  /**
   * Retrieve the encryption information for this uri.
   *
   * @param mUri either an instance URI (if previously saved) or a form URI
   * @param instanceMetadata
   * @return
   */
  public static EncryptedFormInformation getEncryptedFormInformation(
      Uri mUri, FormController.InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
      if (cr.getType(mUri) == InstanceProviderAPI.InstanceColumns.CONTENT_ITEM_TYPE) {
        // chain back to the Form record...
        String[] selectionArgs = null;
        String selection = null;
        Cursor instanceCursor = null;
        try {
          instanceCursor = cr.query(mUri, null, null, null, null);
          if (instanceCursor.getCount() != 1) {
            Log.e(t, "Not exactly one record for this instance!");
            return null; // save unencrypted.
          }
          instanceCursor.moveToFirst();
          String jrFormId =
              instanceCursor.getString(
                  instanceCursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_FORM_ID));
          int idxJrVersion =
              instanceCursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_VERSION);
          if (!instanceCursor.isNull(idxJrVersion)) {
            selectionArgs = new String[] {jrFormId, instanceCursor.getString(idxJrVersion)};
            selection =
                FormsProviderAPI.FormsColumns.JR_FORM_ID
                    + " =? AND "
                    + FormsProviderAPI.FormsColumns.JR_VERSION
                    + "=?";
          } else {
            selectionArgs = new String[] {jrFormId};
            selection =
                FormsProviderAPI.FormsColumns.JR_FORM_ID
                    + " =? AND "
                    + FormsProviderAPI.FormsColumns.JR_VERSION
                    + " IS NULL";
          }
        } finally {
          if (instanceCursor != null) {
            instanceCursor.close();
          }
        }

        formCursor =
            cr.query(
                FormsProviderAPI.FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

        if (formCursor.getCount() != 1) {
          Log.e(t, "Not exactly one blank form matches this jr_form_id");
          return null; // save unencrypted
        }
        formCursor.moveToFirst();
      } else if (cr.getType(mUri) == FormsProviderAPI.FormsColumns.CONTENT_ITEM_TYPE) {
        formCursor = cr.query(mUri, null, null, null, null);
        if (formCursor.getCount() != 1) {
          Log.e(t, "Not exactly one blank form!");
          return null; // save unencrypted.
        }
        formCursor.moveToFirst();
      }

      formId =
          formCursor.getString(formCursor.getColumnIndex(FormsProviderAPI.FormsColumns.JR_FORM_ID));
      if (formId == null || formId.length() == 0) {
        Log.e(t, "No FormId specified???");
        return null;
      }
      int idxVersion = formCursor.getColumnIndex(FormsProviderAPI.FormsColumns.JR_VERSION);
      int idxBase64RsaPublicKey =
          formCursor.getColumnIndex(FormsProviderAPI.FormsColumns.BASE64_RSA_PUBLIC_KEY);
      formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
      String base64RsaPublicKey =
          formCursor.isNull(idxBase64RsaPublicKey)
              ? null
              : formCursor.getString(idxBase64RsaPublicKey);

      if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
        return null; // this is legitimately not an encrypted form
      }

      int version = android.os.Build.VERSION.SDK_INT;
      if (version < 8) {
        Log.e(t, "Phone does not support encryption.");
        return null; // save unencrypted
      }

      // this constructor will throw an exception if we are not
      // running on version 8 or above (if Base64 is not found).
      try {
        wrapper = new Base64Wrapper();
      } catch (ClassNotFoundException e) {
        Log.e(t, "Phone does not have Base64 class but API level is " + version);
        e.printStackTrace();
        return null; // save unencrypted
      }

      // OK -- Base64 decode (requires API Version 8 or higher)
      byte[] publicKey = wrapper.decode(base64RsaPublicKey);
      X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
      KeyFactory kf;
      try {
        kf = KeyFactory.getInstance(RSA_ALGORITHM);
      } catch (NoSuchAlgorithmException e) {
        Log.e(t, "Phone does not support RSA encryption.");
        e.printStackTrace();
        return null;
      }
      try {
        pk = kf.generatePublic(publicKeySpec);
      } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        Log.e(t, "Invalid RSA public key.");
        return null;
      }
    } finally {
      if (formCursor != null) {
        formCursor.close();
      }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
      Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
      return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
      Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
      return null;
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
      return null;
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
      Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
      return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
  }