Example #1
0
 public PublicKey getRawPublicKey() throws SshException {
   try {
     PublicKey key;
     String keyAlg = getString();
     if (KeyPairProvider.SSH_RSA.equals(keyAlg)) {
       BigInteger e = getMPInt();
       BigInteger n = getMPInt();
       KeyFactory keyFactory = SecurityUtils.getKeyFactory("RSA");
       key = keyFactory.generatePublic(new RSAPublicKeySpec(n, e));
     } else if (KeyPairProvider.SSH_DSS.equals(keyAlg)) {
       BigInteger p = getMPInt();
       BigInteger q = getMPInt();
       BigInteger g = getMPInt();
       BigInteger y = getMPInt();
       KeyFactory keyFactory = SecurityUtils.getKeyFactory("DSA");
       key = keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g));
     } else {
       throw new IllegalStateException("Unsupported algorithm: " + keyAlg);
     }
     return key;
   } catch (InvalidKeySpecException e) {
     throw new SshException(e);
   } catch (NoSuchAlgorithmException e) {
     throw new SshException(e);
   } catch (NoSuchProviderException e) {
     throw new SshException(e);
   }
 }
  private void testKeyFactory() throws Exception {
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");

    ECCurve curve =
        new ECCurve.Fp(
            new BigInteger(
                "883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec ecSpec =
        new ECParameterSpec(
            curve,
            curve.decodePoint(
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC");

    config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, ecSpec);

    g.initialize(null, new SecureRandom());

    KeyPair p = g.generateKeyPair();

    ECPrivateKey sKey = (ECPrivateKey) p.getPrivate();
    ECPublicKey vKey = (ECPublicKey) p.getPublic();

    KeyFactory fact = KeyFactory.getInstance("ECDSA", "SC");

    vKey = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), null));
    sKey = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), null));

    testECDSA(sKey, vKey);

    testBCParamsAndQ(sKey, vKey);
    testEC5Params(sKey, vKey);

    testEncoding(sKey, vKey);

    ECPublicKey vKey2 = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), ecSpec));
    ECPrivateKey sKey2 =
        (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), ecSpec));

    if (!vKey.equals(vKey2) || vKey.hashCode() != vKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    if (!sKey.equals(sKey2) || sKey.hashCode() != sKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    // check we can get specs.
    fact.getKeySpec(vKey, java.security.spec.ECPublicKeySpec.class);

    fact.getKeySpec(sKey, java.security.spec.ECPrivateKeySpec.class);
  }
Example #3
0
 private static void testPublic(KeyFactory kf, PublicKey key) throws Exception {
   System.out.println("Testing public key...");
   PublicKey key2 = (PublicKey) kf.translateKey(key);
   KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class);
   PublicKey key3 = kf.generatePublic(keySpec);
   KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class);
   PublicKey key4 = kf.generatePublic(x509Spec);
   KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded());
   PublicKey key5 = kf.generatePublic(x509Spec2);
   testKey(key, key);
   testKey(key, key2);
   testKey(key, key3);
   testKey(key, key4);
   testKey(key, key5);
 }
Example #4
0
  public static KeyPair LoadKeyPair(String path, String algorithm)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
  }
Example #5
0
 /**
  * Generates Public Key from BASE64 encoded string
  *
  * @param key BASE64 encoded string which represents the key
  * @return The PublicKey
  * @throws java.lang.Exception
  */
 public static PublicKey getPublicKeyFromString(String key) throws Exception {
   BASE64Decoder b64 = new BASE64Decoder();
   KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
   EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64.decodeBuffer(key));
   PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
   return publicKey;
 }
Example #6
0
 /**
  * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
  *
  * @param keyBytes
  * @return
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeySpecException
  */
 public static PublicKey getPublicKey(byte[] keyBytes)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(RSA);
   PublicKey publicKey = keyFactory.generatePublic(keySpec);
   return publicKey;
 }
Example #7
0
 @Override
 protected Key initEncryptKey() throws Exception {
   KeyFactory mykeyFactory = KeyFactory.getInstance(getAlgorithm());
   X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(getEncryptKey());
   PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
   return pubKey;
 }
Example #8
0
 private KeyPair loadKey(final JSONObject keys) {
   if (keys == null) {
     return null;
   }
   synchronized (keys) {
     try {
       BigInteger x = new BigInteger(keys.getString("otr_x"), 16);
       BigInteger y = new BigInteger(keys.getString("otr_y"), 16);
       BigInteger p = new BigInteger(keys.getString("otr_p"), 16);
       BigInteger q = new BigInteger(keys.getString("otr_q"), 16);
       BigInteger g = new BigInteger(keys.getString("otr_g"), 16);
       KeyFactory keyFactory = KeyFactory.getInstance("DSA");
       DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, p, q, g);
       DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
       PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
       PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
       return new KeyPair(publicKey, privateKey);
     } catch (JSONException e) {
       return null;
     } catch (NoSuchAlgorithmException e) {
       return null;
     } catch (InvalidKeySpecException e) {
       return null;
     }
   }
 }
  private static void _initKeys() {
    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();

    if ((classLoader == null) || (_encryptedSymmetricKey != null)) {
      return;
    }

    try {
      URL url = classLoader.getResource("com/liferay/portal/license/public.key");

      byte[] bytes = IOUtils.toByteArray(url.openStream());

      X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes);

      KeyFactory keyFactory = KeyFactory.getInstance("RSA");

      PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

      KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

      keyGenerator.init(128, new SecureRandom());

      _symmetricKey = keyGenerator.generateKey();

      byte[] encryptedSymmetricKey =
          Encryptor.encryptUnencoded(publicKey, _symmetricKey.getEncoded());

      _encryptedSymmetricKey = Base64.objectToString(encryptedSymmetricKey);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
Example #10
0
 public void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception {
   DSAPublicKeySpec dsaPubKeySpec =
       new DSAPublicKeySpec(
           new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g));
   PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);
   signature.initVerify(pubKey);
 }
  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);
  }
Example #13
0
 /**
  * 公钥加密
  *
  * @param data 源数据
  * @param publicKey 公钥(BASE64编码)
  * @return
  * @throws Exception
  */
 public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
   byte[] keyBytes = Base64.decode(publicKey);
   X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   Key publicK = keyFactory.generatePublic(x509KeySpec);
   // 对数据加密
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, publicK);
   int inputLen = data.length;
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int offSet = 0;
   byte[] cache;
   int i = 0;
   // 对数据分段加密
   while (inputLen - offSet > 0) {
     if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
       cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
     } else {
       cache = cipher.doFinal(data, offSet, inputLen - offSet);
     }
     out.write(cache, 0, cache.length);
     i++;
     offSet = i * MAX_ENCRYPT_BLOCK;
   }
   byte[] encryptedData = out.toByteArray();
   out.close();
   return encryptedData;
 }
Example #14
0
 @Override
 public byte[] getDhResult(byte[] aMsg, int offset, boolean isLegacyClient) throws ZrtpException {
   try {
     int PV_LENGTH = keyType.pvLengthInWords * 4;
     byte[] encodedKey = new byte[keyType.pvLengthInWords * 4 + 1];
     encodedKey[0] = 4;
     System.arraycopy(aMsg, offset, encodedKey, 1, encodedKey.length - 1);
     EncodedKeySpec keySpec = getSpec(encodedKey, keyPair.getPublic());
     PublicKey pub = keyFactory.generatePublic(keySpec);
     KeyAgreement agreement = KeyAgreement.getInstance(algorithm, "ZBC");
     agreement.init(keyPair.getPrivate());
     agreement.doPhase(pub, true);
     byte[] secret = agreement.generateSecret();
     byte[] iDHResult = null;
     if (!isLegacyClient) {
       iDHResult = new byte[secret.length];
       System.arraycopy(secret, 0, iDHResult, 0, secret.length);
     } else {
       iDHResult = new byte[PV_LENGTH];
       System.arraycopy(secret, 0, iDHResult, iDHResult.length - secret.length, secret.length);
     }
     return iDHResult;
   } catch (Exception e) {
     throw new ZrtpException(e);
   }
 }
  public PublicKey getPublicCAKey()
      throws InvalidKeySpecException, IOException, NoSuchAlgorithmException,
          NoSuchProviderException {
    ChipAuthenticationPublicKeyInfo info =
        securityInfos.getDefaultChipAuthenticationPublicKeyInfo();
    AlgorithmParameterSpec algorithmParameterSpec =
        securityInfos.getDefaultCADomainParameter().getAlgorithmParameterSpec();
    Type type = securityInfos.getDefaultCADomainParameter().getType();

    PublicKey pubKey = null;
    if (type == Type.ECDH) {
      ECParameterSpec eps = (ECParameterSpec) algorithmParameterSpec;
      DEROctetString dos =
          new DEROctetString(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());

      ECPoint point = new X9ECPoint(eps.getCurve(), dos).getPoint();
      ECPublicKeySpec eks = new ECPublicKeySpec(point, eps);

      pubKey = new JCEECPublicKey(type.toString(), eks);

    } else {

      DHParameterSpec dps = (DHParameterSpec) algorithmParameterSpec;
      ASN1Integer dos =
          new ASN1Integer(info.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
      DHPublicKeySpec keySpec = new DHPublicKeySpec(dos.getPositiveValue(), dps.getP(), dps.getG());
      KeyFactory kf = KeyFactory.getInstance(type.toString());
      return kf.generatePublic(keySpec);
    }

    return pubKey;
  }
  public static PublicKey readPublicKeyFromBytes(byte[] bytes) throws GeneralSecurityException {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    PublicKey key = keyFactory.generatePublic(keySpec);

    return key;
  }
    private static Cipher createCipher(int mode, boolean isPrivate, byte[] key)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
      try {
        KeyFactory factory =
            KeyFactory.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER_ALGORITHM);

        Key keyspec;
        if (isPrivate) {
          keyspec = factory.generatePrivate(new PKCS8EncodedKeySpec(key));
        } else {
          keyspec = factory.generatePublic(new X509EncodedKeySpec(key));
        }

        Cipher cipher = Cipher.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER);
        cipher.init(mode, keyspec);

        return cipher;
      } catch (InvalidKeySpecException e) {
        throw new IllegalConfigurationException(e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalConfigurationException(e);
      } catch (NoSuchPaddingException e) {
        throw new IllegalConfigurationException(e);
      }
    }
Example #18
0
  @Kroll.method
  public String encode(HashMap args) {
    // encode text to cipher text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("plainText");
    String keyString = arg.getString("publicKey");
    byte[] encodedBytes = null;
    Key key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePublic(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.ENCRYPT_MODE, key);
      encodedBytes = c.doFinal(txt.getBytes());
    } catch (Exception e) {
      Log.e(TAG, "RSA encryption error " + e.toString());
    }

    return Base64.encodeToString(encodedBytes, Base64.NO_WRAP);
  }
Example #19
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());
    }
  }
  public PublicKey retrieveJwkKey(String jwkUrl) {
    RSAPublicKey pub = null;

    try {
      String jwkString = restTemplate.getForObject(jwkUrl, String.class);
      JsonObject json = (JsonObject) new JsonParser().parse(jwkString);
      JsonArray getArray = json.getAsJsonArray("keys");
      for (int i = 0; i < getArray.size(); i++) {
        JsonObject object = getArray.get(i).getAsJsonObject();
        String algorithm = object.get("alg").getAsString();

        if (algorithm.equals("RSA")) {
          byte[] modulusByte = Base64.decodeBase64(object.get("mod").getAsString());
          BigInteger modulus = new BigInteger(1, modulusByte);
          byte[] exponentByte = Base64.decodeBase64(object.get("exp").getAsString());
          BigInteger exponent = new BigInteger(1, exponentByte);

          RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
          KeyFactory factory = KeyFactory.getInstance("RSA");
          pub = (RSAPublicKey) factory.generatePublic(spec);
        }
      }

    } catch (HttpClientErrorException e) {
      logger.error("HttpClientErrorException in KeyFetcher.java: ", e);
    } catch (NoSuchAlgorithmException e) {
      logger.error("NoSuchAlgorithmException in KeyFetcher.java: ", e);
    } catch (InvalidKeySpecException e) {
      logger.error("InvalidKeySpecException in KeyFetcher.java: ", e);
    }
    return pub;
  }
  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);
    }
  }
Example #22
0
 /**
  * 生成RSA公钥
  *
  * @param publicKeyStr
  * @return
  * @throws Exception
  */
 public PublicKey generateRSAPublicKey(String publicKeyStr) throws Exception {
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   EncodedKeySpec publicKeySpec =
       new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(publicKeyStr));
   RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
   return publicKey;
 }
Example #23
0
  public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey)
      throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    KeyPairGenerator kpg = null;
    kpg = KeyPairGenerator.getInstance("EC");

    ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256
    kpg.initialize(gps);
    KeyPair apair = kpg.generateKeyPair();
    ECPublicKey apub = (ECPublicKey) apair.getPublic();
    ECParameterSpec aspec = apub.getParams();

    byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false);

    byte[] publicKeybx = new byte[32];
    byte[] publicKeyby = new byte[32];
    System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32);
    System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32);
    BigInteger x = new BigInteger(1, publicKeybx);
    BigInteger y = new BigInteger(1, publicKeyby);

    java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y);
    ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec);
    ECPublicKey cpub = null;
    KeyFactory kfa = null;
    kfa = KeyFactory.getInstance("EC");
    return cpub = (ECPublicKey) kfa.generatePublic(cpubs);
  }
  /**
   * 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);
  }
Example #25
0
  public SymmetricCryptor getSymmetricCryptor(
      byte[] peerPublicKeyBytes, boolean useSealedObject, ClassLoader classLoader)
      throws CryptoException {
    if (privateKey == null) {
      throw new IllegalStateException(
          "KeyGenerator did not successfully generate public key"); //$NON-NLS-1$
    }
    try {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(peerPublicKeyBytes);
      KeyFactory keyFact = KeyFactory.getInstance(ALGORITHM);
      PublicKey publicKey = keyFact.generatePublic(x509KeySpec);

      KeyAgreement ka = KeyAgreement.getInstance(ALGORITHM);
      ka.init(privateKey);
      ka.doPhase(publicKey, true);
      byte[] secret = ka.generateSecret();

      MessageDigest sha = MessageDigest.getInstance(DIGEST);
      byte[] hash = sha.digest(secret);
      byte[] symKey = new byte[keySize / 8];
      System.arraycopy(hash, 0, symKey, 0, symKey.length);
      SymmetricCryptor sc = SymmetricCryptor.getSymmectricCryptor(symKey);
      sc.setUseSealedObject(useSealedObject);
      sc.setClassLoader(classLoader);
      return sc;
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10003, e);
    } catch (InvalidKeySpecException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10004, e);
    } catch (InvalidKeyException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10005, e);
    }
  }
Example #26
0
 // 公钥加密
 public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {
   X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, publicKey);
   return cipher.doFinal(data);
 }
Example #27
0
 public static void publicKey() throws Exception {
   CertificateFactory factory = CertificateFactory.getInstance("X.509");
   Certificate cert = factory.generateCertificate(new FileInputStream(Constant.publickey));
   PublicKey pubKey = cert.getPublicKey();
   X509EncodedKeySpec ksp = new X509EncodedKeySpec(pubKey.getEncoded());
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   publicKey = keyFactory.generatePublic(ksp);
 }
Example #28
0
File: Rsa.java Project: uvbs/Core
  /**
   * @param algorithm
   * @param ins
   * @return
   * @throws NoSuchAlgorithmException
   * @throws AlipayException
   */
  private static PublicKey getPublicKeyFromX509(String algorithm, String bysKey)
      throws NoSuchAlgorithmException, Exception {
    byte[] decodedKey = Base64.decode(bysKey);
    X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);

    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    return keyFactory.generatePublic(x509);
  }
Example #29
0
 public static PublicKey decodePublicKey(DataInput buffer, byte[] receivedRawPublicKey)
     throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
   buffer.readBytes(receivedRawPublicKey);
   X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(receivedRawPublicKey);
   KeyFactory keyFactory = KeyFactory.getInstance("DSA");
   final PublicKey receivedPublicKey = keyFactory.generatePublic(pubKeySpec);
   return receivedPublicKey;
 }
Example #30
0
 @Override
 protected byte[] calculateK() throws Exception {
   KeyFactory myKeyFac = SecurityUtils.getKeyFactory("DH");
   DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g);
   PublicKey yourPubKey = myKeyFac.generatePublic(keySpec);
   myKeyAgree.doPhase(yourPubKey, true);
   return stripLeadingZeroes(myKeyAgree.generateSecret());
 }