示例#1
0
 /** 初始化 DES 实例 */
 public DES() {
   try {
     init("3#6q0/bj");
   } catch (NoSuchProviderException e) {
     e.printStackTrace();
   }
 }
  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);
    }
  }
示例#3
0
 public void writeObject(Object obj, String algorithm, char[] password, SecureRandom random)
     throws IOException {
   try {
     super.writeObject(new MiscPEMGenerator(obj, algorithm, password, random, provider));
   } catch (NoSuchProviderException e) {
     throw new EncryptionException(e.getMessage(), e);
   }
 }
示例#4
0
 private Signature createSignature(String cipherName) throws PGPException {
   try {
     return helper.createSignature(cipherName);
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot create signature: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot create signature: " + e.getMessage(), e);
   }
 }
示例#5
0
 KeyFactory createKeyFactory(String algorithm) throws GeneralSecurityException, PGPException {
   try {
     return helper.createKeyFactory(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot find algorithm: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot find provider: " + e.getMessage(), e);
   }
 }
示例#6
0
 public KeyPairGenerator createKeyPairGenerator(String algorithm) throws GeneralSecurityException {
   try {
     return helper.createKeyPairGenerator(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new GeneralSecurityException("cannot find algorithm: " + e.getMessage());
   } catch (NoSuchProviderException e) {
     throw new GeneralSecurityException("cannot find provider: " + e.getMessage());
   }
 }
示例#7
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);
    }
  }
示例#8
0
  /**
   * Generate a certificate signing request (PKCS#10).
   *
   * @param info A PKCS10CertReqInfo
   * @param privateKey Private key for signing the request
   * @param signatureProvider Name of provider to sign with
   * @param publicKey Public key to include in the request
   * @param explicitEccParameters True if the EC domain parameters should be included (ie. not a
   *     named curve)
   * @return the certificate request data
   */
  public static ICertReqData genCertificateRequest(
      ISignerCertReqInfo info,
      final PrivateKey privateKey,
      final String signatureProvider,
      PublicKey publicKey,
      final boolean explicitEccParameters)
      throws IllegalArgumentException {
    LOG.debug(">genCertificateRequest");
    final Base64SignerCertReqData retval;
    if (info instanceof PKCS10CertReqInfo) {
      PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
      PKCS10CertificationRequest pkcs10;

      if (LOG.isDebugEnabled()) {
        LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
        LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
        LOG.debug("explicitEccParameters: " + explicitEccParameters);
      }

      try {
        // Handle ECDSA key with explicit parameters
        if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
          publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Public key SHA1: " + createKeyHash(publicKey));
          LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(publicKey));
        }

        // Generate request
        final JcaPKCS10CertificationRequestBuilder builder =
            new JcaPKCS10CertificationRequestBuilder(
                new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
        final ContentSigner contentSigner =
            new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                .setProvider(signatureProvider)
                .build(privateKey);
        pkcs10 = builder.build(contentSigner);
        retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
      } catch (IOException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (OperatorCreationException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      } catch (NoSuchProviderException e) {
        throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
      }
      LOG.debug("<genCertificateRequest");
      return retval;
    } else {
      throw new IllegalArgumentException(
          "Unsupported certificate request info type: " + info.getClass().getName());
    }
  }
示例#9
0
  public JSONObject httpsRequest(String requestUrl, String httpMethod, String defaultStr) {
    JSONObject res = new JSONObject();
    try {
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new SecureRandom());
      SSLSocketFactory sf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setSSLSocketFactory(sf);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.setRequestMethod(httpMethod);

      if (defaultStr != null) {
        OutputStream os = conn.getOutputStream();
        os.write(defaultStr.getBytes("UTF-8"));
        os.close();
      }

      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "UTF-8");
      BufferedReader br = new BufferedReader(isr);

      String str = null;
      StringBuffer sb = new StringBuffer();
      while ((str = br.readLine()) != null) {
        sb.append(str);
      }
      br.close();
      isr.close();
      is.close();
      is = null;
      conn.disconnect();

      res = JSONObject.fromObject(sb.toString());

    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return res;
  }
示例#10
0
 Cipher createCipher(String cipherName) throws PGPException {
   try {
     return helper.createCipher(cipherName);
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   } catch (NoSuchPaddingException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   }
 }
示例#11
0
  MessageDigest createDigest(int algorithm) throws GeneralSecurityException, PGPException {
    MessageDigest dig;

    try {
      dig = helper.createDigest(PGPUtil.getDigestName(algorithm));
    } catch (NoSuchAlgorithmException e) {
      throw new PGPException("cannot find algorithm: " + e.getMessage(), e);
    } catch (NoSuchProviderException e) {
      throw new PGPException("cannot find provider: " + e.getMessage(), e);
    }

    return dig;
  }
示例#12
0
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 13:00:33.157 -0500",
     hash_original_method = "FE40F27E2DA82EBBE9E1DFDF41871C25",
     hash_generated_method = "5958F652D3CAD7EAE6B4AE73C8917183")
 public void writeObject(Object obj, String algorithm, char[] password, SecureRandom random)
     throws IOException {
   try {
     super.writeObject(new MiscPEMGenerator(obj, algorithm, password, random, provider));
   } catch (NoSuchProviderException e) {
     throw new EncryptionException(e.getMessage(), e);
   }
 }
示例#13
0
 public Long getChallenge() {
   if (challenge == null) {
     SecureRandom random;
     try {
       random = SecureRandom.getInstance("SHA1PRNG", "SUN");
     } catch (NoSuchAlgorithmException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     } catch (NoSuchProviderException ex) {
       random = new SecureRandom();
       LOGGER.error(ex.getMessage(), ex);
     }
     random.setSeed((new Date()).getTime());
     challenge = random.nextLong() % (10 ^ 6);
   }
   return challenge;
 }
示例#14
0
  public X509Certificate convertCertificate(X509CertificateHolder certHolder)
      throws CertificateException {

    try {
      CertificateFactory certFact = helper.createCertificateFactory("X.509");

      return (X509Certificate)
          certFact.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
    } catch (IOException e) {
      throw new OpCertificateException(
          "cannot get encoded form of certificate: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      throw new OpCertificateException("cannot create certificate factory: " + e.getMessage(), e);
    } catch (NoSuchProviderException e) {
      throw new OpCertificateException("cannot find factory provider: " + e.getMessage(), e);
    }
  }
  private PublicKey getECPublicKeyPublicKey(ECDSAPublicKey key)
      throws EACException, InvalidKeySpecException {
    ECParameterSpec spec = getParams(key);
    java.security.spec.ECPoint publicPoint = getPublicPoint(key);
    ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(publicPoint, spec);

    KeyFactory factk;
    try {
      factk = helper.createKeyFactory("ECDSA");
    } catch (NoSuchProviderException e) {
      throw new EACException("cannot find provider: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      throw new EACException("cannot find algorithm ECDSA: " + e.getMessage(), e);
    }

    return factk.generatePublic(pubKeySpec);
  }
示例#16
0
  static {
    try {
      sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      TrustManager[] tm = {new BaseTrustManager()};
      sslContext.init(null, tm, new java.security.SecureRandom());
      ssf = sslContext.getSocketFactory();

    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#17
0
  static boolean verify(final X509CRL crl, final PublicKey publicKey, final boolean silent)
      throws NoSuchAlgorithmException, CRLException, InvalidKeyException, SignatureException {

    if (crl instanceof X509CRLObject) {
      final CertificateList crlList = (CertificateList) getCertificateList(crl);
      final AlgorithmIdentifier tbsSignatureId = crlList.getTBSCertList().getSignature();
      if (!crlList.getSignatureAlgorithm().equals(tbsSignatureId)) {
        if (silent) return false;
        throw new CRLException(
            "Signature algorithm on CertificateList does not match TBSCertList.");
      }

      final Signature signature = getSignature(crl.getSigAlgName(), securityProvider);

      signature.initVerify(publicKey);
      signature.update(crl.getTBSCertList());

      if (!signature.verify(crl.getSignature())) {
        if (silent) return false;
        throw new SignatureException("CRL does not verify with supplied public key.");
      }
      return true;
    }

    try {
      crl.verify(publicKey);
      return true;
    } catch (NoSuchAlgorithmException ex) {
      if (silent) return false;
      throw ex;
    } catch (CRLException ex) {
      if (silent) return false;
      throw ex;
    } catch (InvalidKeyException ex) {
      if (silent) return false;
      throw ex;
    } catch (SignatureException ex) {
      if (silent) return false;
      throw ex;
    } catch (NoSuchProviderException e) {
      if (isDebug()) e.printStackTrace();
      throw new RuntimeException(e); // unexpected - might hide a bug
    }
  }
 public Cipher getCipher()
     throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
         NoSuchPaddingException {
   ++ivSeedArray[ivCounter % ivSeedArray.length];
   ++ivCounter;
   IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray);
   Cipher c = null;
   try {
     c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, "BC");
     isNotBouncyCastle = false;
   } catch (NoSuchProviderException e) {
     Log.w(t, "Unable to obtain BouncyCastle provider! Decryption may fail!");
     e.printStackTrace();
     isNotBouncyCastle = true;
     c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM);
   }
   c.init(Cipher.ENCRYPT_MODE, symmetricKey, baseIv);
   return c;
 }
示例#19
0
  /**
   * Creates a CertPath of the specified type. This constructor is protected because most users
   * should use a CertificateFactory to create CertPaths.
   */
  PKIXCertPath(InputStream inStream, String encoding) throws CertificateException {
    super("X.509");
    try {
      if (encoding.equalsIgnoreCase("PkiPath")) {
        ASN1InputStream derInStream = new ASN1InputStream(inStream);
        ASN1Primitive derObject = derInStream.readObject();
        if (!(derObject instanceof ASN1Sequence)) {
          throw new CertificateException(
              "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
        }
        Enumeration e = ((ASN1Sequence) derObject).getObjects();
        certificates = new ArrayList();
        CertificateFactory certFactory =
            CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        while (e.hasMoreElements()) {
          ASN1Encodable element = (ASN1Encodable) e.nextElement();
          byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER);
          certificates.add(0, certFactory.generateCertificate(new ByteArrayInputStream(encoded)));
        }
      } else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM")) {
        inStream = new BufferedInputStream(inStream);
        certificates = new ArrayList();
        CertificateFactory certFactory =
            CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        Certificate cert;
        while ((cert = certFactory.generateCertificate(inStream)) != null) {
          certificates.add(cert);
        }
      } else {
        throw new CertificateException("unsupported encoding: " + encoding);
      }
    } catch (IOException ex) {
      throw new CertificateException(
          "IOException throw while decoding CertPath:\n" + ex.toString());
    } catch (NoSuchProviderException ex) {
      throw new CertificateException(
          "BouncyCastle provider not found while trying to get a CertificateFactory:\n"
              + ex.toString());
    }

    this.certificates = sortCerts(certificates);
  }
  public PublicKey getKey(PublicKeyDataObject publicKeyDataObject)
      throws EACException, InvalidKeySpecException {
    if (publicKeyDataObject.getUsage().on(EACObjectIdentifiers.id_TA_ECDSA)) {
      return getECPublicKeyPublicKey((ECDSAPublicKey) publicKeyDataObject);
    } else {
      RSAPublicKey pubKey = (RSAPublicKey) publicKeyDataObject;
      RSAPublicKeySpec pubKeySpec =
          new RSAPublicKeySpec(pubKey.getModulus(), pubKey.getPublicExponent());

      try {
        KeyFactory factk = helper.createKeyFactory("RSA");

        return factk.generatePublic(pubKeySpec);
      } catch (NoSuchProviderException e) {
        throw new EACException("cannot find provider: " + e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        throw new EACException("cannot find algorithm ECDSA: " + e.getMessage(), e);
      }
    }
  }
示例#21
0
  public static byte[] decrypt(byte[] content, String pwd) {
    KeyGenerator kgen = null;
    try {
      Log.i("shentanli", "in the decrypt");
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");

      sr.setSeed(pwd.getBytes());
      kgen.init(128, sr);
      SecretKey sk = kgen.generateKey();
      byte[] ef = sk.getEncoded();
      SecretKeySpec key = new SecretKeySpec(ef, "AES");
      Cipher c = null;
      c = Cipher.getInstance("AES/ECB/NoPadding");

      c.init(Cipher.DECRYPT_MODE, key);
      //     byte[] tmp = Base64.decode(content.getBytes("UTF-8"), Base64.DEFAULT);
      //   byte[] tmp = parseHexStr2Byte(content);
      byte[] result = c.doFinal(content);
      Log.i("shentanli", "now to return");
      //  Log.i("shentanli---", Base64.encodeToString(result, Base64.DEFAULT));
      //   return Base64.encodeToString(result, Base64.DEFAULT);
      Log.i("shentanli", new String(result));
      //  return (new String(result));
      return result;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
    }

    return content;
  }
示例#22
0
  /**
   * Constructor SignatureDSA
   *
   * @throws XMLSignatureException
   */
  public SignatureDSA() throws XMLSignatureException {
    String algorithmID = JCEMapper.translateURItoJCEID(SignatureDSA.URI);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
      log.log(java.util.logging.Level.FINE, "Created SignatureDSA using " + algorithmID);
    }

    String provider = JCEMapper.getProviderId();
    try {
      if (provider == null) {
        this.signatureAlgorithm = Signature.getInstance(algorithmID);
      } else {
        this.signatureAlgorithm = Signature.getInstance(algorithmID, provider);
      }
    } catch (java.security.NoSuchAlgorithmException ex) {
      Object[] exArgs = {algorithmID, ex.getLocalizedMessage()};
      throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    } catch (java.security.NoSuchProviderException ex) {
      Object[] exArgs = {algorithmID, ex.getLocalizedMessage()};
      throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
    }
  }
 @Override
 public MetadataObject resolve(X509Certificate attestationCertificate) {
   String issuer = attestationCertificate.getIssuerDN().getName();
   for (X509Certificate cert : certs.get(issuer)) {
     try {
       attestationCertificate.verify(cert.getPublicKey());
       return metadata.get(cert);
     } catch (CertificateException e) {
       e.printStackTrace();
     } catch (NoSuchAlgorithmException e) {
       e.printStackTrace();
     } catch (InvalidKeyException e) {
       e.printStackTrace();
     } catch (NoSuchProviderException e) {
       e.printStackTrace();
     } catch (SignatureException e) {
       e.printStackTrace();
     }
   }
   return null;
 }
示例#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;
 }
示例#25
0
 Cipher createKeyWrapper(int encAlgorithm) throws PGPException {
   try {
     switch (encAlgorithm) {
       case SymmetricKeyAlgorithmTags.AES_128:
       case SymmetricKeyAlgorithmTags.AES_192:
       case SymmetricKeyAlgorithmTags.AES_256:
         return helper.createCipher("AESWrap");
       case SymmetricKeyAlgorithmTags.CAMELLIA_128:
       case SymmetricKeyAlgorithmTags.CAMELLIA_192:
       case SymmetricKeyAlgorithmTags.CAMELLIA_256:
         return helper.createCipher("CamelliaWrap");
       default:
         throw new PGPException("unknown wrap algorithm: " + encAlgorithm);
     }
   } catch (NoSuchAlgorithmException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   } catch (NoSuchPaddingException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   } catch (NoSuchProviderException e) {
     throw new PGPException("cannot create cipher: " + e.getMessage(), e);
   }
 }
  public Boolean verifySignature(byte[] originalData, byte[] signedData) {
    boolean verified = false;

    try {
      Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
      sig.initVerify(getPublicKey());
      sig.update(originalData, 0, originalData.length);
      verified = sig.verify(signedData);
    } catch (SignatureException ex) {
      ex.printStackTrace();
      Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null);
    } catch (InvalidKeyException ex) {
      ex.printStackTrace();
      Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null);
    } catch (NoSuchAlgorithmException ex) {
      ex.printStackTrace();
      Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null);
    } catch (NoSuchProviderException ex) {
      ex.printStackTrace();
      Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null);
    }

    return verified;
  }
示例#27
0
  @Override
  public boolean verifySignature(Object message, byte[] signatureToVerify) {
    //        return true;

    try {
      Signature newSig = Signature.getInstance(CryptoUtil.ALGORITHM, CryptoUtil.PROVIDER);
      newSig.initVerify(publicKey);
      byte[] byteRep = CryptoUtil.convertToJsonByteArray(message);
      newSig.update(byteRep);
      newSig.verify(signatureToVerify);

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

    return true;
  }
  /**
   * 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);
  }
        @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("");
            }
          }
        }
示例#30
0
  /**
   * Performs test signatures for the specified keys or for all if "all" specified.
   *
   * @param keyStore Loaded keystore to read keys from
   * @param alias Alias of key to test or "all" to test all
   * @param authCode Key password (if used, ie for JKS only)
   * @param signatureProvider Provider for creating the signature
   * @return The results for each key found
   * @throws CryptoTokenOfflineException In case the key could not be used
   */
  public static Collection<KeyTestResult> testKey(
      KeyStore keyStore, String alias, char[] authCode, String signatureProvider)
      throws CryptoTokenOfflineException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("testKey for alias: " + alias);
    }

    final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>();

    try {
      final Enumeration<String> e = keyStore.aliases();
      while (e.hasMoreElements()) {
        final String keyAlias = e.nextElement();
        if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          if (keyStore.isKeyEntry(keyAlias)) {
            String status;
            String publicKeyHash = null;
            boolean success = false;
            try {
              final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode);
              final Certificate entryCert = keyStore.getCertificate(keyAlias);
              if (entryCert != null) {
                final PublicKey publicKey = entryCert.getPublicKey();
                publicKeyHash = createKeyHash(publicKey);
                testSignAndVerify(privateKey, publicKey, signatureProvider);
                success = true;
                status = "";
              } else {
                status = "Not testing keys with alias " + keyAlias + ". No certificate exists.";
              }
            } catch (ClassCastException ce) {
              status = "Not testing keys with alias " + keyAlias + ". Not a private key.";
            } catch (InvalidKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (KeyStoreException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchAlgorithmException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchProviderException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (SignatureException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (UnrecoverableKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            }
            result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash));
          }
        }
      }
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("<testKey");
    }
    return result;
  }