/** java.security.KeyStore#getKey(java.lang.String, char[]) */
  public void test_getKeyLjava_lang_String$C() throws Exception {

    // Test for method java.security.Key
    // java.security.KeyStore.getKey(java.lang.String, char[])
    // creatCertificate();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, null);

    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);
    PrivateKey returnedKey = (PrivateKey) keyTest.getKey("alias2", pssWord);
    byte[] retB = returnedKey.getEncoded();
    byte[] priB = getPrivateKey().getEncoded();
    assertTrue(Arrays.equals(retB, priB));
    assertEquals(getPrivateKey().getAlgorithm(), returnedKey.getAlgorithm());
    assertEquals(getPrivateKey().getFormat(), returnedKey.getFormat());

    try {
      keyTest.getKey("alias2", "wrong".toCharArray());
      fail();
    } catch (UnrecoverableKeyException expected) {
    }

    keyTest.setCertificateEntry("alias1", cert[1]);
    assertNull(
        "the private key returned from getKey for a certificate entry is not null",
        keyTest.getKey("alias1", pssWord));
  }
Esempio n. 2
0
  /**
   * Sign the provided payment request.
   *
   * @param paymentRequest Payment request to sign, in its builder form.
   * @param certificateChain Certificate chain to send with the payment request, ordered from client
   *     certificate to root certificate. The root certificate itself may be omitted.
   * @param privateKey The key to sign with. Must match the public key from the first certificate of
   *     the certificate chain.
   */
  public static void signPaymentRequest(
      Protos.PaymentRequest.Builder paymentRequest,
      X509Certificate[] certificateChain,
      PrivateKey privateKey) {
    try {
      final Protos.X509Certificates.Builder certificates = Protos.X509Certificates.newBuilder();
      for (final Certificate certificate : certificateChain)
        certificates.addCertificate(ByteString.copyFrom(certificate.getEncoded()));

      paymentRequest.setPkiType("x509+sha256");
      paymentRequest.setPkiData(certificates.build().toByteString());
      paymentRequest.setSignature(ByteString.EMPTY);
      final Protos.PaymentRequest paymentRequestToSign = paymentRequest.build();

      final String algorithm;
      if ("RSA".equalsIgnoreCase(privateKey.getAlgorithm())) algorithm = "SHA256withRSA";
      else throw new IllegalStateException(privateKey.getAlgorithm());

      final Signature signature = Signature.getInstance(algorithm);
      signature.initSign(privateKey);
      signature.update(paymentRequestToSign.toByteArray());

      paymentRequest.setSignature(ByteString.copyFrom(signature.sign()));
    } catch (final GeneralSecurityException x) {
      // Should never happen so don't make users have to think about it.
      throw new RuntimeException(x);
    }
  }
  @Test
  public void testKeygenToFileOutputStream()
      throws NoSuchAlgorithmException, NoSuchProviderException, IOException {
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();

    final PrivateKey priv = pair.getPrivate();
    final PublicKey pub = pair.getPublic();

    // Write the private key to a file
    FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key");
    Assert.assertNotNull(privOS);
    privOS.write(priv.getEncoded());
    privOS.close();

    // Write the private key to a file
    FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key");
    Assert.assertNotNull(publicOS);
    publicOS.write(pub.getEncoded());
    publicOS.close();
  }
  public void generateLocalKeyPair(String fullUserId) {

    String userId = Address.stripResource(fullUserId);

    OtrDebugLogger.log("generating local key pair for: " + userId);

    KeyPair keyPair;
    try {

      KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALG);
      kpg.initialize(KEY_SIZE);

      keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      OtrDebugLogger.log("no such algorithm", e);
      return;
    }

    OtrDebugLogger.log("SUCCESS! generating local key pair for: " + userId);

    // Store Private Key.
    PrivateKey privKey = keyPair.getPrivate();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());

    this.store.setProperty(userId + ".privateKey", pkcs8EncodedKeySpec.getEncoded());

    // Store Public Key.
    PublicKey pubKey = keyPair.getPublic();
    storeLocalPublicKey(userId, pubKey);

    store.save();
  }
Esempio n. 5
0
  public boolean generateKeys() {

    PublicKey keyPub;
    PrivateKey keyPri;
    SecureRandom rand;

    Security.addProvider(new ABAProvider());

    rand = new SecureRandom();

    rand.setSeed(System.currentTimeMillis());

    try {
      KeyPairGenerator fact;
      KeyPair keyPair;

      fact = KeyPairGenerator.getInstance("RSA", "ABA");

      fact.initialize(1024, rand);

      keyPair = fact.generateKeyPair();

      keyPub = keyPair.getPublic();

      keyPri = keyPair.getPrivate();

      pubKey = bytesToHexStr(keyPub.getEncoded());

      priKey = bytesToHexStr(keyPri.getEncoded());
    } catch (Exception e) {
      return false;
    }
    return true;
  }
Esempio n. 6
0
 @Test
 public void testPrivateKey() throws Exception {
   KeyPair keyPair = KeyPairFactory.newRsa2048();
   String pem = PemUtils.toPem(keyPair.getPrivate());
   assertNotNull(pem);
   PrivateKey privateKey = PemUtils.loadPrivateKeyFromPem(pem);
   assertTrue(privateKey.getAlgorithm().equalsIgnoreCase(BcCmsConstants.KEY_PAIR_ALGO));
 }
Esempio n. 7
0
 private static void dumpKeyPair(KeyPair keyPair) {
   PublicKey pub = keyPair.getPublic();
   System.out.println("Public Key: " + getHexString(pub.getEncoded()));
   System.out.println(
       "Public Key: "
           + "30820222300d06092a864886f70d01010105000382020f003082020a0282020100d7d774dd8a5326b7e17d74796ae19b1ba0d7f905cc9074b4001bed78512bcdf9330b813bf70c5bcf0c389ddb557f6152e144ae0ee6b3b1a5c0a10fd93130ca5470473396e2ffb809e1743654017ed3646ce342f8bda2cb788c6f64b03ba75f9d6bf28bf039bb4c0ccb0c0921ae7f4ba4c6eb6d211fdbdc52677a9a6ef150ac7d15a44eafb510ad16229da438966fb1e9bc6425e67518f99ffadece69935f571f6d375e16fa930335c9656386525042e8c35b2c4286410267911960542ddef1c620d30a631c2d41f2be09bd6df0eaad3333987e8c94c42691d97695701ae2ac0e1e48ea925c86cbaf48ccdc8353a51ca6e95236a4de948028ffde2ffa44f5888a411fb02dfe6f77ea40057714b02a7f7a22173d6f09336bb39a2067ae67cdf26d5ab652850d897b31013a0dfae1a6b24c3713670b6ec45ecae586996f65e00d50a258d8d061e9b69cb61571c97ec5ceeb2c343f43e9c17d9ce1a6107ab241631f1ca556ae821f7a6c468f13bb6da0fc27a15189b8b58d43c5b9a5d3e06d2689d399ba3567a55f2de1440e035746c87bdcf0635588f9d000aeb3bd0122e233010b454a7e5131e2061f82ca1a5c81b54faf269afa2ef4aeb6ae5b2a79cbb1ac9e770ecd138b66178d0267232a379bcd191358ff4a3374a819a93966188708d3991605c5d5f89146086fb048600116268fab91867434ed0c599d643b7ce313a1a4450203010001");
   PrivateKey priv = keyPair.getPrivate();
   System.out.println("Private Key: " + getHexString(priv.getEncoded()));
 }
 // 私钥加密
 public static byte[] encryptByPrivateKey(String key, byte[] data) throws Exception {
   // 实例化密钥材�?
   PKCS8EncodedKeySpec pcs8spec = new PKCS8EncodedKeySpec(Base64.decode(key.getBytes()));
   // 实例化密钥工�?
   KeyFactory keyfactory = KeyFactory.getInstance(Key_ALGORITHM);
   // 生成私钥
   PrivateKey pritekey = keyfactory.generatePrivate(pcs8spec);
   // 私钥加密
   Cipher cipher = Cipher.getInstance(pritekey.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, pritekey);
   return cipher.doFinal(data);
 }
Esempio n. 9
0
  @Test
  public void testX509Helpers() throws Exception {
    KeyPair keyPair = SAMLUtils.generateRandomKeyPair();

    String privateKeyString = SAMLUtils.savePrivateKey(keyPair.getPrivate());
    String publicKeyString = SAMLUtils.savePublicKey(keyPair.getPublic());

    PrivateKey privateKey = SAMLUtils.loadPrivateKey(privateKeyString);
    PublicKey publicKey = SAMLUtils.loadPublicKey(publicKeyString);

    assertTrue(privateKey.equals(keyPair.getPrivate()));
    assertTrue(publicKey.equals(keyPair.getPublic()));
  }
Esempio n. 10
0
 public PrivateKey getPrivateKey(String alias) {
   PrivateKey pk = keyManager.getPrivateKey(alias);
   if (Debug.verboseOn())
     Debug.logVerbose(
         "getPrivateKey for alias ["
             + alias
             + "] got "
             + (pk == null
                 ? "[Not Found!]"
                 : "[alg:" + pk.getAlgorithm() + ";format:" + pk.getFormat() + "]"),
         module);
   // Debug.logInfo(new Exception(), "Location where getPrivateKey is called", module);
   return pk;
 }
Esempio n. 11
0
  /**
   * Creates a test signature and verifies it.
   *
   * @param privateKey Private key to sign with
   * @param publicKey Public key to verify with
   * @param signatureProvider Name of provider to sign with
   * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
   * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not
   *     installed
   * @throws InvalidKeyException If signature verification failed or the key was invalid
   * @throws SignatureException If the signature could not be made or verified correctly
   */
  public static void testSignAndVerify(
      PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
      throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException,
          SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
      throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
      LOG.debug("testSigAlg: " + sigAlg);
      LOG.debug("provider: " + signatureProvider);
      LOG.trace("privateKey: " + privateKey);
      LOG.trace("privateKey class: " + privateKey.getClass().getName());
      LOG.trace("publicKey: " + publicKey);
      LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
      LOG.trace("Created signature of size: " + signBA.length);
      LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
      throw new InvalidKeyException("Test signature inconsistent");
    }
  }
Esempio n. 12
0
  private void validateKeys(PublicKey pubKey, PrivateKey privKey) {

    if (pubKey.getAlgorithm() != privKey.getAlgorithm())
      throw new IllegalArgumentException("Public and private key have different algorithms");

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA") return;

    try {

      String data = "ENCRYPT_DATA";
      SecureRandom random = new SecureRandom();
      Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
      byte[] encryptedData = cipher.doFinal(data.getBytes());

      cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
      String decreptedData = new String(cipher.doFinal(encryptedData));
      if (!decreptedData.equals(data)) throw new IllegalArgumentException("Bad public-private key");

    } catch (BadPaddingException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (IllegalBlockSizeException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (NoSuchPaddingException e) {
      throw new IllegalArgumentException("Bad public-private key", e);
    } catch (InvalidKeyException e) {
      throw new IllegalArgumentException("Invalid public-private key", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid algorithm for public-private key", e);
    }
  }
Esempio n. 13
0
  public static void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream fos = new FileOutputStream(path + "/public.key");
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    fos = new FileOutputStream(path + "/private.key");
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
  }
Esempio n. 14
0
  /**
   * 使用口令加密私钥(Base64编码)
   *
   * @return
   */
  public String encryptPrivateKey(String passphrase) {
    byte[] seeds = null;
    byte[] raw = mMyPrivKey.getEncoded();
    byte[] encrypted = null;

    Cipher cipher;
    try {
      seeds = getRawKey(passphrase.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(seeds, PASS_ALGO);
      cipher = Cipher.getInstance(PASS_ALGO);
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      encrypted = 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();
    }

    String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
    return result;
  }
Esempio n. 15
0
 public static String toPem(PrivateKey privateKey) throws CertificateEncodingException {
   checkNotNull(privateKey, "Private key cannot be null.");
   Base64 encoder = new Base64(Base64.PEM_CHUNK_SIZE);
   return BEGIN_PRIVATE_KEY
       + NEW_LINE
       + encoder.encodeToString(privateKey.getEncoded())
       + END_PRIVATE_KEY;
 }
  /**
   * Create a new PKCS#7 object from the specified key.
   *
   * @param privKey the private key to be used for signing.
   * @param certChain the certificate chain associated with the private key.
   * @param crlList the crl list associated with the private key.
   * @param hashAlgorithm the hashing algorithm used to compute the message digest. Must be "MD5",
   *     "MD2", "SHA1" or "SHA"
   * @param provider the provider to use.
   */
  public PKCS7SignedData(
      PrivateKey privKey,
      Certificate[] certChain,
      CRL[] crlList,
      String hashAlgorithm,
      String provider)
      throws SecurityException, InvalidKeyException, NoSuchProviderException,
          NoSuchAlgorithmException {
    this.privKey = privKey;

    if (hashAlgorithm.equals("MD5")) {
      digestAlgorithm = ID_MD5;
    } else if (hashAlgorithm.equals("MD2")) {
      digestAlgorithm = ID_MD2;
    } else if (hashAlgorithm.equals("SHA")) {
      digestAlgorithm = ID_SHA1;
    } else if (hashAlgorithm.equals("SHA1")) {
      digestAlgorithm = ID_SHA1;
    } else {
      throw new NoSuchAlgorithmException("Unknown Hash Algorithm " + hashAlgorithm);
    }

    version = signerversion = 1;
    certs = new ArrayList();
    crls = new ArrayList();
    digestalgos = new HashSet();
    digestalgos.add(digestAlgorithm);

    //
    // Copy in the certificates and crls used to sign the private key.
    //
    signCert = (X509Certificate) certChain[0];
    for (int i = 0; i < certChain.length; i++) {
      certs.add(certChain[i]);
    }

    if (crlList != null) {
      for (int i = 0; i < crlList.length; i++) {
        crls.add(crlList[i]);
      }
    }

    //
    // Now we have private key, find out what the digestEncryptionAlgorithm is.
    //
    digestEncryptionAlgorithm = privKey.getAlgorithm();
    if (digestEncryptionAlgorithm.equals("RSA")) {
      digestEncryptionAlgorithm = ID_RSA;
    } else if (digestEncryptionAlgorithm.equals("DSA")) {
      digestEncryptionAlgorithm = ID_DSA;
    } else {
      throw new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm);
    }

    sig = Signature.getInstance(getDigestAlgorithm(), provider);

    sig.initSign(privKey);
  }
Esempio n. 17
0
 public static void writePrivateKeyToFile(String filename, PrivateKey key) throws CryptoException {
   byte[] privKeyBytes = key.getEncoded();
   EncodedKeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
   try {
     writeFile(filename, ks.getEncoded());
   } catch (IOException e) {
     throw new CryptoException(e);
   }
 }
Esempio n. 18
0
  private static Object getOpenSSLKeyForPrivateKey(PrivateKey privateKey) {
    // Sanity checks
    if (privateKey == null) {
      Log.e(TAG, "privateKey == null");
      return null;
    }
    if (!(privateKey instanceof RSAPrivateKey)) {
      Log.e(TAG, "does not implement RSAPrivateKey");
      return null;
    }
    // First, check that this is a proper instance of OpenSSLRSAPrivateKey
    // or one of its sub-classes.
    Class<?> superClass;
    try {
      superClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLRSAPrivateKey");
    } catch (Exception e) {
      // This may happen if the target device has a completely different
      // implementation of the java.security APIs, compared to vanilla
      // Android. Highly unlikely, but still possible.
      Log.e(TAG, "Cannot find system OpenSSLRSAPrivateKey class: " + e);
      return null;
    }
    if (!superClass.isInstance(privateKey)) {
      // This may happen if the PrivateKey was not created by the "AndroidOpenSSL"
      // provider, which should be the default. That could happen if an OEM decided
      // to implement a different default provider. Also highly unlikely.
      Log.e(
          TAG,
          "Private key is not an OpenSSLRSAPrivateKey instance, its class name is:"
              + privateKey.getClass().getCanonicalName());
      return null;
    }

    try {
      // Use reflection to invoke the 'getOpenSSLKey()' method on the
      // private key. This returns another Java object that wraps a native
      // EVP_PKEY and OpenSSLEngine. Note that the method is final in Android
      // 4.1, so calling the superclass implementation is ok.
      Method getKey = superClass.getDeclaredMethod("getOpenSSLKey");
      getKey.setAccessible(true);
      Object opensslKey = null;
      try {
        opensslKey = getKey.invoke(privateKey);
      } finally {
        getKey.setAccessible(false);
      }
      if (opensslKey == null) {
        // Bail when detecting OEM "enhancement".
        Log.e(TAG, "getOpenSSLKey() returned null");
        return null;
      }
      return opensslKey;
    } catch (Exception e) {
      Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
      return null;
    }
  }
 /**
  * Called by JNI when the native HTTPS stack gets a client certificate request.
  *
  * <p>We delegate the request to CallbackProxy, and route its response to {@link
  * #nativeSslClientCert(int, X509Certificate)}.
  */
 private void requestClientCert(int handle, String hostAndPort) {
   SslClientCertLookupTable table = SslClientCertLookupTable.getInstance();
   if (table.IsAllowed(hostAndPort)) {
     // previously allowed
     PrivateKey pkey = table.PrivateKey(hostAndPort);
     if (pkey instanceof OpenSSLKeyHolder) {
       OpenSSLKey sslKey = ((OpenSSLKeyHolder) pkey).getOpenSSLKey();
       nativeSslClientCert(handle, sslKey.getPkeyContext(), table.CertificateChain(hostAndPort));
     } else {
       nativeSslClientCert(handle, pkey.getEncoded(), table.CertificateChain(hostAndPort));
     }
   } else if (table.IsDenied(hostAndPort)) {
     // previously denied
     nativeSslClientCert(handle, 0, null);
   } else {
     // previously ignored or new
     mCallbackProxy.onReceivedClientCertRequest(
         new ClientCertRequestHandler(this, handle, hostAndPort, table), hostAndPort);
   }
 }
Esempio n. 20
0
  /**
   * Creates the content signer for generation of Version 1 {@link
   * java.security.cert.X509Certificate}.
   *
   * @param privateKey the private key
   * @return the content signer
   */
  public static ContentSigner createSigner(PrivateKey privateKey) {
    try {
      AlgorithmIdentifier sigAlgId =
          new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
      AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

      return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
          .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (Exception e) {
      throw new RuntimeException("Could not create content signer.", e);
    }
  }
  @Override
  public KeyType getKeyType() throws CVKeyTypeNotSupportedException {
    String strAlgo = m_key.getAlgorithm();

    if ("RSA".equals(strAlgo)) {
      return KeyType.KEY_RSA;
    } else if ("EC".equals(strAlgo) || "ECC".equals(strAlgo) || "ECDSA".equals(strAlgo)) {
      return KeyType.KEY_ECDSA;
    }

    throw new CVKeyTypeNotSupportedException();
  }
Esempio n. 22
0
  /**
   * Sign a given message with a given PrivateKey object. This method shall only be used to
   * implement signing in the context of SSL client certificate support.
   *
   * <p>The message will actually be a hash, computed by OpenSSL itself, depending on the type of
   * the key. The result should match exactly what the vanilla implementations of the following
   * OpenSSL function calls do:
   *
   * <p>- For a RSA private key, this should be equivalent to calling RSA_private_encrypt(...,
   * RSA_PKCS1_PADDING), i.e. it must generate a raw RSA signature. The message must be either a
   * combined, 36-byte MD5+SHA1 message digest or a DigestInfo value wrapping a message digest.
   *
   * <p>- For a ECDSA private keys, this should be equivalent to calling ECDSA_sign(0,...). The
   * message must be a hash and the function shall compute a direct ECDSA signature for it.
   *
   * @param privateKey The PrivateKey handle.
   * @param message The message to sign.
   * @return signature as a byte buffer.
   *     <p>Important: Due to a platform bug, this function will always fail on Android < 4.2 for
   *     RSA PrivateKey objects. See the getOpenSSLHandleForPrivateKey() below for work-around.
   */
  @CalledByNative
  private static byte[] rawSignDigestWithPrivateKey(PrivateKey privateKey, byte[] message) {
    // Get the Signature for this key.
    Signature signature = null;
    // Hint: Algorithm names come from:
    // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
    try {
      String keyAlgorithm = privateKey.getAlgorithm();
      if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
        // IMPORTANT: Due to a platform bug, this will throw NoSuchAlgorithmException
        // on Android 4.1.x. Fixed in 4.2 and higher.
        // See https://android-review.googlesource.com/#/c/40352/
        signature = Signature.getInstance("NONEwithRSA");
      } else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
        signature = Signature.getInstance("NONEwithECDSA");
      }
    } catch (NoSuchAlgorithmException e) {
      // Intentionally do nothing.
    }

    if (signature == null) {
      Log.e(TAG, "Unsupported private key algorithm: " + privateKey.getAlgorithm());
      return null;
    }

    // Sign the message.
    try {
      signature.initSign(privateKey);
      signature.update(message);
      return signature.sign();
    } catch (Exception e) {
      Log.e(
          TAG,
          "Exception while signing message with "
              + privateKey.getAlgorithm()
              + " private key: "
              + e);
      return null;
    }
  }
Esempio n. 23
0
  /*
   * 产生RSA公私钥对
   */
  public static void genRSAKeyPair() {
    KeyPairGenerator rsaKeyGen = null;
    KeyPair rsaKeyPair = null;
    try {
      System.out.println("Generating a pair of RSA key ... ");
      rsaKeyGen = KeyPairGenerator.getInstance("RSA");
      SecureRandom random = new SecureRandom();
      random.setSeed(System.currentTimeMillis());

      // rsaKeyGen.initialize(1024, random);
      rsaKeyGen.initialize(1024);
      rsaKeyPair = rsaKeyGen.genKeyPair();
      PublicKey rsaPublic = rsaKeyPair.getPublic();
      PrivateKey rsaPrivate = rsaKeyPair.getPrivate();

      System.out.println("公钥:" + bytesToHexStr(rsaPublic.getEncoded()));
      System.out.println("私钥:" + bytesToHexStr(rsaPrivate.getEncoded()));
      System.out.println("1024-bit RSA key GENERATED.");
    } catch (Exception e) {
      System.out.println("genRSAKeyPair:" + e);
    }
  }
Esempio n. 24
0
  @Override
  public String toString() {
    String s = ""; // $NON-NLS-1$

    // s += "This is the user data for user " +i + ": " + "\n";
    if (SK != null) {
      s +=
          Messages.UserData_ECBDII_1
              + SK.toString().substring(0, SK.toString().indexOf('\n'))
              + "\n"; //$NON-NLS-2$
    }
    if (PK != null) {
      s +=
          Messages.UserData_ECBDII_3
              + PK.toString().substring(0, PK.toString().indexOf('\n'))
              + "\n"; //$NON-NLS-2$
    }
    if (nonce != null) {
      s += Messages.UserData_ECBDII_5 + nonce.toString() + "\n"; // $NON-NLS-2$
    }
    if (DHKeyPair != null) {
      if (DHKeyPair.getSK() != null && !DHKeyPair.getSK().toString().equals("")) { // $NON-NLS-1$
        s += Messages.UserData_ECBDII_0;
        s += DHKeyPair.getSK().toString() + "\n"; // $NON-NLS-1$
      }
      if (DHKeyPair.getPK() != null && !DHKeyPair.getPK().GetPrintP().equals("")) { // $NON-NLS-1$
        s += Messages.UserData_ECBDII_11;
        s += DHKeyPair.getPK().GetPrintP() + "\n"; // $NON-NLS-1$
      }
    }
    if (Xvalue != null && !Xvalue.PrintP().equals("")) { // $NON-NLS-1$
      s += Messages.UserData_ECBDII_14 + Xvalue.PrintP() + "\n"; // $NON-NLS-2$
    }
    if (key != null && !key.PrintP().equals("")) { // $NON-NLS-1$
      s += Messages.UserData_ECBDII_17 + key.PrintP() + "\n"; // $NON-NLS-2$
    }

    return s;
  }
Esempio n. 25
0
 // internal implementation of translateKey() for private keys. See JCA doc
 private PrivateKey translatePrivateKey(PrivateKey key) throws InvalidKeyException {
   if (key instanceof RSAPrivateCrtKey) {
     if (key instanceof RSAPrivateCrtKeyImpl) {
       return key;
     }
     RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
     try {
       return new RSAPrivateCrtKeyImpl(
           rsaKey.getModulus(),
           rsaKey.getPublicExponent(),
           rsaKey.getPrivateExponent(),
           rsaKey.getPrimeP(),
           rsaKey.getPrimeQ(),
           rsaKey.getPrimeExponentP(),
           rsaKey.getPrimeExponentQ(),
           rsaKey.getCrtCoefficient());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPrivateCrtKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if (key instanceof RSAPrivateKey) {
     if (key instanceof RSAPrivateKeyImpl) {
       return key;
     }
     RSAPrivateKey rsaKey = (RSAPrivateKey) key;
     try {
       return new RSAPrivateKeyImpl(rsaKey.getModulus(), rsaKey.getPrivateExponent());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPrivateKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if ("PKCS#8".equals(key.getFormat())) {
     byte[] encoded = key.getEncoded();
     return RSAPrivateCrtKeyImpl.newKey(encoded);
   } else {
     throw new InvalidKeyException(
         "Private keys must be instance " + "of RSAPrivate(Crt)Key or have PKCS#8 encoding");
   }
 }
Esempio n. 26
0
  private String decryptCredential(final String cred) {
    try {
      final PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean();
      factory.setAlgorithm("RSA");
      factory.setLocation(new ClassPathResource("RSA1024Private.p8"));
      factory.setSingleton(false);
      final PrivateKey privateKey = factory.getObject();

      logger.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm());
      final Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());

      logger.debug("Decoding value [{}]", cred);
      final byte[] cred64 = CompressionUtils.decodeBase64ToByteArray(cred);

      logger.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, privateKey);

      final byte[] cipherData = cipher.doFinal(cred64);
      return new String(cipherData);
    } catch (final Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 27
0
 /*
  * 模拟与银行整个交互过程
  */
 public static void main(String[] args) {
   try {
     // 银行产生RSA 公钥私钥,自己保留私钥,把公钥发给用友
     KeyPair keys = instance.generateRSAKeyPair("syj".getBytes());
     PublicKey pubkey = keys.getPublic();
     PrivateKey prikey = keys.getPrivate();
     String pubKeyStr = new BASE64Encoder().encodeBuffer(pubkey.getEncoded());
     String priKeyStr = new BASE64Encoder().encodeBuffer(prikey.getEncoded());
     System.out.println("pubKey = " + pubKeyStr);
     System.out.println("priKey = " + priKeyStr);
     // 银行产生AES密钥
     byte[] aesKyeByte = instance.generateAesByte("atrcdfdsfs".getBytes());
     System.out.println("beforeEncAesKyeStr = " + new BASE64Encoder().encodeBuffer(aesKyeByte));
     // 银行用RSA私钥加密AES密钥,然后将加密后的aesEncStr返回给用友
     String aesEncStr =
         instance.encryptAesSeed(
             new BASE64Encoder().encodeBuffer(aesKyeByte),
             instance.generateRSAPrivateKey(priKeyStr));
     System.out.println("加密后的秘钥 = " + aesEncStr);
     // 用友用RSA公钥解密aesEncStr得到AES明文
     byte[] aesDecBytes =
         instance.decryptAesSeed(aesEncStr, instance.generateRSAPublicKey(pubKeyStr));
     System.out.println("afterDecAesKyeStr = " + new BASE64Encoder().encodeBuffer(aesDecBytes));
     // 用友用AES加密发送xml报文给银行
     String requestXml = instance.generateXml();
     System.out.println("beforeEncXml = " + requestXml);
     SecretKey secretKey = instance.generateAESSecretKey(aesDecBytes);
     String base64RequestXml = instance.encryptRequestXml(requestXml, secretKey);
     // 银行解密收到的xml报文
     String resultXml = instance.decryptResultXml(base64RequestXml, secretKey);
     System.out.println("afterDecXml = " + resultXml);
     // 银行将结果xml用AES加密后返回给用友
     // 用友用AES解密报文,完成整个交互流程
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Esempio n. 28
0
  public static String getPrivate(String path, String pwd) {
    try {
      KeyStore ks = KeyStore.getInstance("PKCS12");
      FileInputStream is = new FileInputStream(path);
      ks.load(is, pwd.toCharArray());
      is.close();
      System.out.println("keystore type=" + ks.getType());
      Enumeration enuma = ks.aliases();
      String keyAlias = null;
      if (enuma.hasMoreElements()) {
        keyAlias = (String) enuma.nextElement();
        System.out.println("alias=[" + keyAlias + "]");
      }

      System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));
      BASE64Encoder enc = new BASE64Encoder();
      PrivateKey privatekey = (PrivateKey) ks.getKey(keyAlias, pwd.toCharArray());
      System.out.println("private key = " + enc.encode(privatekey.getEncoded()));
      return enc.encode(privatekey.getEncoded());
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * Generate a local key pair. Be careful. If there is already an key pair, it will override it
   *
   * @param sessionID the sessionID that is identified with the local machine
   */
  public void generateLocalKeyPair(SessionID sessionID) {
    if (sessionID == null) return;

    String accountID = sessionID.getAccountID();
    KeyPair keyPair;
    try {
      keyPair = KeyPairGenerator.getInstance("DSA").genKeyPair();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return;
    }

    // Store Public Key.
    PublicKey pubKey = keyPair.getPublic();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded());

    this.store.setProperty(accountID + ".publicKey", x509EncodedKeySpec.getEncoded());

    // Store Private Key.
    PrivateKey privKey = keyPair.getPrivate();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());

    this.store.setProperty(accountID + ".privateKey", pkcs8EncodedKeySpec.getEncoded());
  }
Esempio n. 30
0
  /**
   * 生成公匙和私匙
   *
   * @param seed 种子
   * @return
   * @throws Exception
   */
  public static Map<String, String> generateKey(String seed) throws Exception {
    Map<String, String> map = new HashMap<String, String>(2);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

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

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

    System.out.println("publicKey: " + map.get("public"));
    System.out.println("privateKey: " + map.get("private"));
    return map;
  }