@Test
  public void testGenerateRSA() {
    /*
     * Init Provider
     */
    ProviderManagement providerManagement = new ProviderManagement();
    providerManagement.initProvider("BC");
    /*
     * Generate Key RSA 1024-bit
     * return KeyPair
     */
    int lengthKeyRSA = 1024;
    String cryptoProvider = "BC";

    KeyManagementRSA keyManagementRSA = new KeyManagementRSA();
    KeyPair keyPair = keyManagementRSA.generateRSA(lengthKeyRSA, cryptoProvider);

    /*
     * Get Modulus & Exponent Public Key
     */
    RSAPublicKey rsaPubKey = (RSAPublicKey) keyPair.getPublic();

    /*
     * Test Result
     */
    assertEquals(lengthKeyRSA, rsaPubKey.getModulus().bitLength());
  }
 private Map<String, Object> createRSAJWK(RSAPublicKey key, KeyUse use, String alg)
     throws ServerException {
   String alias = null;
   try {
     alias = getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.KEYSTORE_ALIAS);
   } catch (SSOException | SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
   if (StringUtils.isBlank(alias)) {
     logger.error("Alias of ID Token Signing Key not set.");
     throw new ServerException("Alias of ID Token Signing Key not set.");
   } else if ("test".equals(alias)) {
     logger.warning("Alias of ID Token Signing Key should be changed from default, 'test'.");
   }
   String kid =
       Hash.hash(alias + key.getModulus().toString() + key.getPublicExponent().toString());
   return json(object(
           field("kty", "RSA"),
           field(OAuth2Constants.JWTTokenParams.KEY_ID, kid),
           field("use", use.toString()),
           field("alg", alg),
           field("n", Base64url.encode(key.getModulus().toByteArray())),
           field("e", Base64url.encode(key.getPublicExponent().toByteArray()))))
       .asMap();
 }
示例#3
0
  /**
   * Creates a {@code KeyValueType} that wraps the specified public key. This method supports DSA
   * and RSA keys.
   *
   * @param key the {@code PublicKey} that will be represented as a {@code KeyValueType}.
   * @return the constructed {@code KeyValueType} or {@code null} if the specified key is neither a
   *     DSA nor a RSA key.
   */
  public static KeyValueType createKeyValue(PublicKey key) {
    if (key instanceof RSAPublicKey) {
      RSAPublicKey pubKey = (RSAPublicKey) key;
      byte[] modulus = pubKey.getModulus().toByteArray();
      byte[] exponent = pubKey.getPublicExponent().toByteArray();

      RSAKeyValueType rsaKeyValue = new RSAKeyValueType();
      rsaKeyValue.setModulus(Base64.encodeBytes(modulus).getBytes());
      rsaKeyValue.setExponent(Base64.encodeBytes(exponent).getBytes());
      return rsaKeyValue;
    } else if (key instanceof DSAPublicKey) {
      DSAPublicKey pubKey = (DSAPublicKey) key;
      byte[] P = pubKey.getParams().getP().toByteArray();
      byte[] Q = pubKey.getParams().getQ().toByteArray();
      byte[] G = pubKey.getParams().getG().toByteArray();
      byte[] Y = pubKey.getY().toByteArray();

      DSAKeyValueType dsaKeyValue = new DSAKeyValueType();
      dsaKeyValue.setP(Base64.encodeBytes(P).getBytes());
      dsaKeyValue.setQ(Base64.encodeBytes(Q).getBytes());
      dsaKeyValue.setG(Base64.encodeBytes(G).getBytes());
      dsaKeyValue.setY(Base64.encodeBytes(Y).getBytes());
      return dsaKeyValue;
    }
    throw logger.unsupportedType(key.toString());
  }
示例#4
0
 private String getString(PublicKey key) throws FailedLoginException {
   try {
     if (key instanceof DSAPublicKey) {
       DSAPublicKey dsa = (DSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-dss");
       write(dos, dsa.getParams().getP());
       write(dos, dsa.getParams().getQ());
       write(dos, dsa.getParams().getG());
       write(dos, dsa.getY());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else if (key instanceof RSAKey) {
       RSAPublicKey rsa = (RSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-rsa");
       write(dos, rsa.getPublicExponent());
       write(dos, rsa.getModulus());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else {
       throw new FailedLoginException("Unsupported key type " + key.getClass().toString());
     }
   } catch (IOException e) {
     throw new FailedLoginException("Unable to check public key");
   }
 }
  /** 生成密钥对 */
  public static Map<String, String> generateKeyPair() throws Exception {
    /** RSA算法要求有一个可信任的随机数源 */
    SecureRandom sr = new SecureRandom();
    /** 为RSA算法创建一个KeyPairGenerator对象 */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
    kpg.initialize(KEYSIZE, sr);
    /** 生成密匙对 */
    KeyPair kp = kpg.generateKeyPair();
    /** 得到公钥 */
    Key publicKey = kp.getPublic();
    byte[] publicKeyBytes = publicKey.getEncoded();
    String pub =
        new String(Base64.encodeBase64(publicKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING);
    /** 得到私钥 */
    Key privateKey = kp.getPrivate();
    byte[] privateKeyBytes = privateKey.getEncoded();
    String pri =
        new String(Base64.encodeBase64(privateKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING);

    Map<String, String> map = new HashMap<String, String>();
    map.put("publicKey", pub);
    map.put("privateKey", pri);
    RSAPublicKey rsp = (RSAPublicKey) kp.getPublic();
    BigInteger bint = rsp.getModulus();
    byte[] b = bint.toByteArray();
    byte[] deBase64Value = Base64.encodeBase64(b);
    String retValue = new String(deBase64Value);
    map.put("modulus", retValue);
    return map;
  }
  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }

    if (o instanceof OpenSSLRSAPublicKey) {
      OpenSSLRSAPublicKey other = (OpenSSLRSAPublicKey) o;

      /*
       * We can shortcut the true case, but it still may be equivalent but
       * different copies.
       */
      if (key.equals(other.getOpenSSLKey())) {
        return true;
      }
    }

    if (!(o instanceof RSAPublicKey)) {
      return false;
    }

    ensureReadParams();

    RSAPublicKey other = (RSAPublicKey) o;
    return modulus.equals(other.getModulus()) && publicExponent.equals(other.getPublicExponent());
  }
  /**
   * Certificate_Verify(証明書)を受け取ったときの動作をします。
   *
   * @param line クライアントから受信した文字列
   * @return クライアントの証明書の真偽
   * @author kinbara
   */
  private boolean recieveCertificateVerify(String line) {
    boolean cert_verify = false;
    // サーバー側のダイジェストのハッシュ値
    ListIterator listIte = netDigest.listIterator();
    String digest = "";
    while (listIte.hasNext()) {
      digest += listIte.next().toString();
    }
    digest = digest.substring(0, digest.indexOf("Certificate_Verify"));
    BigInteger digest1 = new BigInteger(this.getHash(digest), 16);
    // クライアントの公開鍵で復号
    BigInteger digest2 = new BigInteger(line.substring(line.indexOf(":") + 1), 16);
    try {
      X509 x509 = new X509("src/sglserver/conf/key/ca", "CAKeyStore", this.storePasswd);
      // TODO:(注意)ユーザーの公開鍵をpeerNameでCAKeyStoreに登録している場合のみ有効
      RSAPublicKey pk = x509.getRSAPublicKey(peerName);
      digest2 = digest2.modPow(pk.getPublicExponent(), pk.getModulus()); // 復号
      // b = a.modPow(s, n); → a mod n のs乗がbに代入される
      // pk.getPublicExponent()→公開指数
      // pk.getModulus()→pkのmod値
    } catch (Exception e) {

      e.printStackTrace();
    }
    if (digest1.compareTo(digest2) == 0) {
      System.out.println(socket.getRemoteSocketAddress() + "は、信頼できます。");
      cert_verify = true;
    } else {
      System.out.println(socket.getRemoteSocketAddress() + "は、危険です。");
    }
    return (cert_verify);
  }
示例#8
0
 /**
  * 打印公钥信息
  *
  * @param publicKey
  */
 public static void printPublicKeyInfo(PublicKey publicKey) {
   RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
   System.out.println("----------RSAPublicKey----------");
   System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
   System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
   System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
   System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
 }
示例#9
0
 private static RsaPublicKey readRsaX509Certificate(PublicKey publicKey, Padding padding)
     throws KeyczarException {
   RSAPublicKey jceKey = (RSAPublicKey) publicKey;
   RsaPublicKey key = new RsaPublicKey();
   key.set(jceKey.getModulus().bitLength(), jceKey.getModulus(), jceKey.getPublicExponent());
   key.setPadding(padding == null ? Padding.OAEP : padding);
   return key;
 }
示例#10
0
 public String getPublicKey() {
   RSAPublicKey publicKey = cipherMgr.getPublicKey();
   if (null != publicKey) {
     return Base64Utils.encode(publicKey.getEncoded());
   } else {
     return null;
   }
 }
示例#11
0
  /**
   * Convert a public key to the SSH format.
   *
   * <p>Note that only RSA keys are supported at the moment.
   *
   * @param key the public key to convert
   * @return an array of bytes that can with the representation of the public key
   */
  public static byte[] getKeyBytes(final PublicKey key) {
    // We only support RSA at the moment:
    if (!(key instanceof RSAPublicKey)) {
      log.error(
          "The key algorithm \"" + key.getAlgorithm() + "\" is not supported, will return null.");
      return null;
    }

    // Extract the bytes of the exponent and the modulus
    // of the key:
    final RSAPublicKey rsaKey = (RSAPublicKey) key;
    final byte[] exponentBytes = rsaKey.getPublicExponent().toByteArray();
    final byte[] modulusBytes = rsaKey.getModulus().toByteArray();
    if (log.isDebugEnabled()) {
      log.debug(
          "Exponent is "
              + rsaKey.getPublicExponent()
              + " ("
              + Hex.encodeHexString(exponentBytes)
              + ").");
      log.debug(
          "Modulus is " + rsaKey.getModulus() + " (" + Hex.encodeHexString(exponentBytes) + ").");
    }

    try {
      // Prepare the stream to write the binary SSH key:
      final ByteArrayOutputStream binaryOut = new ByteArrayOutputStream();
      final DataOutputStream dataOut = new DataOutputStream(binaryOut);

      // Write the SSH header (4 bytes for the length of the algorithm
      // name and then the algorithm name):
      dataOut.writeInt(SSH_RSA.length());
      dataOut.writeBytes(SSH_RSA);

      // Write the exponent and modulus bytes (note that it is not
      // necessary to check if the most significative bit is one, as
      // that will never happen with byte arrays created from big
      // integers, unless they are negative, which is not the case
      // for RSA modulus or exponents):
      dataOut.writeInt(exponentBytes.length);
      dataOut.write(exponentBytes);
      dataOut.writeInt(modulusBytes.length);
      dataOut.write(modulusBytes);

      // Done, extract the bytes:
      binaryOut.close();
      final byte[] keyBytes = binaryOut.toByteArray();
      if (log.isDebugEnabled()) {
        log.debug("Key bytes are " + Hex.encodeHexString(keyBytes) + ".");
      }

      return keyBytes;
    } catch (IOException exception) {
      log.error("Error while serializing public key, will return null.", exception);
      return null;
    }
  }
示例#12
0
 /** 根据公钥获取key */
 private static byte[] getPKBytes(PublicKey pk) {
   if (pk instanceof RSAPublicKey) {
     RSAPublicKey k = (RSAPublicKey) pk;
     return k.getModulus().toByteArray();
   } else if (pk instanceof DSAPublicKey) {
     DSAPublicKey k = (DSAPublicKey) pk;
     return k.getY().toByteArray();
   }
   return null;
 }
示例#13
0
 /**
  * 这个方法用于生成密钥,如果已经有密钥了就不需要在调用方法生成了
  *
  * @return
  * @throws Exception
  */
 public static Map<String, String> initKey() throws Exception {
   KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
   keyPairGen.initialize(KEY_SIZE);
   KeyPair keyPair = keyPairGen.generateKeyPair();
   RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
   RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
   Map<String, String> keyMap = new HashMap<String, String>();
   keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
   keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
   return keyMap;
 }
示例#14
0
 protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
     throws InvalidKeySpecException {
   try {
     // convert key to one of our keys
     // this also verifies that the key is a valid RSA key and ensures
     // that the encoding is X.509/PKCS#8 for public/private keys
     key = engineTranslateKey(key);
   } catch (InvalidKeyException e) {
     throw new InvalidKeySpecException(e);
   }
   if (key instanceof RSAPublicKey) {
     RSAPublicKey rsaKey = (RSAPublicKey) key;
     if (rsaPublicKeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()));
     } else if (x509KeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new X509EncodedKeySpec(key.getEncoded()));
     } else {
       throw new InvalidKeySpecException(
           "KeySpec must be RSAPublicKeySpec or " + "X509EncodedKeySpec for RSA public keys");
     }
   } else if (key instanceof RSAPrivateKey) {
     if (pkcs8KeySpecClass.isAssignableFrom(keySpec)) {
       return keySpec.cast(new PKCS8EncodedKeySpec(key.getEncoded()));
     } else if (rsaPrivateCrtKeySpecClass.isAssignableFrom(keySpec)) {
       if (key instanceof RSAPrivateCrtKey) {
         RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) key;
         return keySpec.cast(
             new RSAPrivateCrtKeySpec(
                 crtKey.getModulus(),
                 crtKey.getPublicExponent(),
                 crtKey.getPrivateExponent(),
                 crtKey.getPrimeP(),
                 crtKey.getPrimeQ(),
                 crtKey.getPrimeExponentP(),
                 crtKey.getPrimeExponentQ(),
                 crtKey.getCrtCoefficient()));
       } else {
         throw new InvalidKeySpecException("RSAPrivateCrtKeySpec can only be used with CRT keys");
       }
     } else if (rsaPrivateKeySpecClass.isAssignableFrom(keySpec)) {
       RSAPrivateKey rsaKey = (RSAPrivateKey) key;
       return keySpec.cast(
           new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()));
     } else {
       throw new InvalidKeySpecException(
           "KeySpec must be RSAPrivate(Crt)KeySpec or "
               + "PKCS8EncodedKeySpec for RSA private keys");
     }
   } else {
     // should not occur, caught in engineTranslateKey()
     throw new InvalidKeySpecException("Neither public nor private key");
   }
 }
 private static void test(PrivateKey privateKey, PublicKey publicKey) throws Exception {
   testSignature("MD2withRSA", privateKey, publicKey);
   testSignature("MD5withRSA", privateKey, publicKey);
   testSignature("SHA1withRSA", privateKey, publicKey);
   testSignature("SHA224withRSA", privateKey, publicKey);
   testSignature("SHA256withRSA", privateKey, publicKey);
   RSAPublicKey rsaKey = (RSAPublicKey) publicKey;
   if (rsaKey.getModulus().bitLength() > 512) {
     // for SHA384 and SHA512 the data is too long for 512 bit keys
     testSignature("SHA384withRSA", privateKey, publicKey);
     testSignature("SHA512withRSA", privateKey, publicKey);
   }
 }
示例#16
0
  protected int engineGetKeySize(Key key) {
    if (key instanceof RSAPrivateKey) {
      RSAPrivateKey k = (RSAPrivateKey) key;

      return k.getModulus().bitLength();
    } else if (key instanceof RSAPublicKey) {
      RSAPublicKey k = (RSAPublicKey) key;

      return k.getModulus().bitLength();
    }

    throw new IllegalArgumentException("not an RSA key!");
  }
示例#17
0
  protected void assertsRsaKey(RSAPublicKey pubKey) {
    Assert.assertEquals(new BigInteger("65537"), pubKey.getPublicExponent());

    final String modulus =
        "22840028388110743583131987675136887114153126223124011317437832666"
            + "25854781992306722377061897219550740787245366580892823047038154958086308817575397"
            + "86207323511183698710582016112357060923053840856777454937186677760616034425665662"
            + "82261472797239839649294119764258671908502475664743909024714305171394796349355615"
            + "01410512875834037603865586850446929492793894140130256172372280205701912961974382"
            + "44718040286649900869581969011709834002741504113088991590355018061303753262915348"
            + "56911333402703872012358714368938812147820774134682975669390306870781321673316754"
            + "378035200080485404740444851779733064858474545694849794752210968120764651";
    Assert.assertEquals(new BigInteger(modulus), pubKey.getModulus());
  }
 @Override
 protected SignerWithRecovery getRSASigner() {
   SignerWithRecovery signer = null;
   try {
     RSAEngine rsa = new RSAEngine();
     RSAPublicKey pub = (RSAPublicKey) getPublicKey(aaFile);
     RSAKeyParameters pubParameters =
         new RSAKeyParameters(false, pub.getModulus(), pub.getPublicExponent());
     signer = new ISO9796d2Signer(rsa, new SHA256Digest(), false);
     signer.init(false, pubParameters);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return signer;
 }
示例#19
0
 static OpenSSLKey getInstance(RSAPublicKey rsaPublicKey) throws InvalidKeyException {
   try {
     return new OpenSSLKey(
         NativeCrypto.EVP_PKEY_new_RSA(
             rsaPublicKey.getModulus().toByteArray(),
             rsaPublicKey.getPublicExponent().toByteArray(),
             null,
             null,
             null,
             null,
             null,
             null));
   } catch (Exception e) {
     throw new InvalidKeyException(e);
   }
 }
示例#20
0
  static byte[] buildRSA(RSAPublicKey key) {
    DataByteOutputStream out = new DataByteOutputStream();
    BigInteger exponent = key.getPublicExponent();
    BigInteger modulus = key.getModulus();
    int exponentLength = BigIntegerLength(exponent);

    if (exponentLength < 256) out.writeByte(exponentLength);
    else {
      out.writeByte(0);
      out.writeShort(exponentLength);
    }
    out.writeBigInteger(exponent);
    out.writeBigInteger(modulus);

    return out.toByteArray();
  }
  @Test
  public void test() {
    ServerCACR serverCACR = new ServerCACR();
    CA_CR_keys cacr_keys = new CA_CR_keys();
    Random rand = new Random();
    BigInteger cegado_cliente = new BigInteger(4, rand);
    System.out.println("antes de encriptar con privKey de la CA ------> " + cegado_cliente);

    BigInteger certificado = serverCACR.certificate(cegado_cliente);
    System.out.println("certificado----------------------------------->" + certificado);

    RSAPublicKey pubKey = CA_CR_keys.getPubKey();
    BigInteger e = pubKey.getPublicExponent();
    BigInteger n = pubKey.getModulus();
    System.out.println(
        "despues de desencriptar con la pública ------->" + certificado.modPow(e, n));
  }
示例#22
0
  @Test
  public void testTrustStore()
      throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    File caPem = getTempFile("ca/cert.pem");
    KeyStore keystore = createKeyStore();

    KeyStoreUtil.updateWithCaPem(keystore, caPem);

    Enumeration<String> aliases = keystore.aliases();
    String alias = aliases.nextElement();
    assertFalse(aliases.hasMoreElements());
    assertTrue(alias.contains("ca.test.jolokia.org"));
    X509Certificate cert = (X509Certificate) keystore.getCertificate(alias);
    cert.checkValidity();
    assertTrue(cert.getSubjectDN().getName().contains(CA_CERT_SUBJECT_DN_CN));
    RSAPublicKey key = (RSAPublicKey) cert.getPublicKey();
    assertEquals(key.getAlgorithm(), "RSA");
  }
示例#23
0
  /**
   * 生成密钥对�?�注意这里是生成密钥对KeyPair,再由密钥对获取公私�?
   *
   * @return
   */
  public static Map<String, byte[]> generateKeyBytes() {

    try {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
      keyPairGenerator.initialize(KEY_SIZE);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

      Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
      keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
      keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
      return keyMap;
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
示例#24
0
 // internal implementation of translateKey() for public keys. See JCA doc
 private PublicKey translatePublicKey(PublicKey key) throws InvalidKeyException {
   if (key instanceof RSAPublicKey) {
     if (key instanceof RSAPublicKeyImpl) {
       return key;
     }
     RSAPublicKey rsaKey = (RSAPublicKey) key;
     try {
       return new RSAPublicKeyImpl(rsaKey.getModulus(), rsaKey.getPublicExponent());
     } catch (RuntimeException e) {
       // catch providers that incorrectly implement RSAPublicKey
       throw new InvalidKeyException("Invalid key", e);
     }
   } else if ("X.509".equals(key.getFormat())) {
     byte[] encoded = key.getEncoded();
     return new RSAPublicKeyImpl(encoded);
   } else {
     throw new InvalidKeyException(
         "Public keys must be instance " + "of RSAPublicKey or have X.509 encoding");
   }
 }
示例#25
0
  /**
   * @param kpair test key pair
   * @param pubExponent expected public exponent.
   * @return true if test passed. false if test failed.
   */
  private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
    boolean passed = true;
    RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
    RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();

    // test the getModulus method
    if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
      if (!priv.getModulus().equals(pub.getModulus())) {
        System.err.println("priv.getModulus() = " + priv.getModulus());
        System.err.println("pub.getModulus() = " + pub.getModulus());
        passed = false;
      }

      if (!pubExponent.equals(pub.getPublicExponent())) {
        System.err.println("pubExponent = " + pubExponent);
        System.err.println("pub.getPublicExponent() = " + pub.getPublicExponent());
        passed = false;
      }
    }
    return passed;
  }
示例#26
0
  protected byte[] getHash(RSAPublicKey publicKey) throws EbicsException {
    String modulus;
    String exponent;
    String hash;
    byte[] digest;

    exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray());
    modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray()));
    hash = exponent + " " + modulus;

    if (hash.charAt(0) == '0') {
      hash = hash.substring(1);
    }

    try {
      digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII"));
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
      throw new EbicsException(e.getMessage());
    }

    return format(new String(Hex.encodeHex(digest, false))).getBytes();
  }
  public PublicKeyDataObject getPublicKeyDataObject(
      ASN1ObjectIdentifier usage, PublicKey publicKey) {
    if (publicKey instanceof java.security.interfaces.RSAPublicKey) {
      java.security.interfaces.RSAPublicKey pubKey =
          (java.security.interfaces.RSAPublicKey) publicKey;

      return new RSAPublicKey(usage, pubKey.getModulus(), pubKey.getPublicExponent());
    } else {
      ECPublicKey pubKey = (ECPublicKey) publicKey;
      java.security.spec.ECParameterSpec params = pubKey.getParams();

      return new ECDSAPublicKey(
          usage,
          ((ECFieldFp) params.getCurve().getField()).getP(),
          params.getCurve().getA(),
          params.getCurve().getB(),
          convertPoint(convertCurve(params.getCurve()), params.getGenerator()).getEncoded(),
          params.getOrder(),
          convertPoint(convertCurve(params.getCurve()), pubKey.getW()).getEncoded(),
          params.getCofactor());
    }
  }
示例#28
0
 private static String encryptByPublicKey(final String data, final RSAPublicKey publicKey)
     throws Exception {
   final Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.ENCRYPT_MODE, publicKey);
   final int key_len = publicKey.getModulus().bitLength() / 8;
   final String[] datas = splitString(data, key_len - 11);
   String mi = "";
   for (final String s : datas) {
     final byte[] mib = cipher.doFinal(s.getBytes());
     mi += bcd2Str(mib);
   }
   return new String(Base64.encodeBase64(ASCII_To_BCD(mi.getBytes(), mi.getBytes().length)));
 }
  protected KeySpec engineGetKeySpec(Key key, Class spec) throws InvalidKeySpecException {
    if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) {
      return new PKCS8EncodedKeySpec(key.getEncoded());
    } else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) {
      return new X509EncodedKeySpec(key.getEncoded());
    } else if (spec.isAssignableFrom(RSAPublicKeySpec.class) && key instanceof RSAPublicKey) {
      RSAPublicKey k = (RSAPublicKey) key;

      return new RSAPublicKeySpec(k.getModulus(), k.getPublicExponent());
    } else if (spec.isAssignableFrom(RSAPrivateKeySpec.class) && key instanceof RSAPrivateKey) {
      RSAPrivateKey k = (RSAPrivateKey) key;

      return new RSAPrivateKeySpec(k.getModulus(), k.getPrivateExponent());
    } else if (spec.isAssignableFrom(RSAPrivateCrtKeySpec.class)
        && key instanceof RSAPrivateCrtKey) {
      RSAPrivateCrtKey k = (RSAPrivateCrtKey) key;

      return new RSAPrivateCrtKeySpec(
          k.getModulus(),
          k.getPublicExponent(),
          k.getPrivateExponent(),
          k.getPrimeP(),
          k.getPrimeQ(),
          k.getPrimeExponentP(),
          k.getPrimeExponentQ(),
          k.getCrtCoefficient());
    } else if (spec.isAssignableFrom(DHPrivateKeySpec.class) && key instanceof DHPrivateKey) {
      DHPrivateKey k = (DHPrivateKey) key;

      return new DHPrivateKeySpec(k.getX(), k.getParams().getP(), k.getParams().getG());
    } else if (spec.isAssignableFrom(DHPublicKeySpec.class) && key instanceof DHPublicKey) {
      DHPublicKey k = (DHPublicKey) key;

      return new DHPublicKeySpec(k.getY(), k.getParams().getP(), k.getParams().getG());
    }

    throw new RuntimeException("not implemented yet " + key + " " + spec);
  }
示例#30
0
文件: RSAUtil.java 项目: pradp/yspro
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {

    File file = new File("c:/test.html");

    FileInputStream in = new FileInputStream(file);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    byte[] tmpbuf = new byte[1024];
    int count = 0;
    while ((count = in.read(tmpbuf)) != -1) {
      bout.write(tmpbuf, 0, count);
      tmpbuf = new byte[1024];
    }

    in.close();
    byte[] orgData = bout.toByteArray();
    KeyPair keyPair = RSAUtil.generateKeyPair();
    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
    byte[] pubModBytes = pubKey.getModulus().toByteArray();
    byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
    // byte[] priModBytes = priKey.getModulus().toByteArray();
    // byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
    RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes, pubPubExpBytes);
    // RSAPrivateKey recoveryPriKey =
    // RSAUtil.generateRSAPrivateKey(priModBytes, priPriExpBytes);
    byte[] raw = RSAUtil.encrypt(priKey, orgData);
    file = new File("c:/encrypt_result.dat");
    OutputStream out = new FileOutputStream(file);
    out.write(raw);
    out.close();
    byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
    file = new File("c:/decrypt_result.html");
    out = new FileOutputStream(file);
    out.write(data);
    out.flush();
    out.close();
  }