示例#1
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;
  }
  @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();
  }
示例#4
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;
  }
  /** 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));
  }
示例#6
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;
 }
示例#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()));
 }
示例#8
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);
   }
 }
  /**
   * 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);
    }
  }
示例#10
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;
    }
  }
示例#11
0
 private static void testPrivate(KeyFactory kf, PrivateKey key) throws Exception {
   System.out.println("Testing private key...");
   PrivateKey key2 = (PrivateKey) kf.translateKey(key);
   KeySpec keySpec = kf.getKeySpec(key, ECPrivateKeySpec.class);
   PrivateKey key3 = kf.generatePrivate(keySpec);
   KeySpec pkcs8Spec = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);
   PrivateKey key4 = kf.generatePrivate(pkcs8Spec);
   KeySpec pkcs8Spec2 = new PKCS8EncodedKeySpec(key.getEncoded());
   PrivateKey key5 = kf.generatePrivate(pkcs8Spec2);
   testKey(key, key);
   testKey(key, key2);
   testKey(key, key3);
   testKey(key, key4);
   testKey(key, key5);
 }
示例#12
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();
  }
 /** Proceed with the specified private key and client certificate chain. */
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 12:32:39.625 -0500",
     hash_original_method = "FD9D9C54290793DEF25EE96780FA43D9",
     hash_generated_method = "0D823BB8817086852D9CC56BB148DF51")
 public void proceed(PrivateKey privateKey, X509Certificate[] chain) {
   byte[] privateKeyBytes = privateKey.getEncoded();
   byte[][] chainBytes;
   try {
     chainBytes = NativeCrypto.encodeCertificates(chain);
   } catch (CertificateEncodingException e) {
     mBrowserFrame.nativeSslClientCert(mHandle, null, null);
     return;
   }
   mTable.Allow(mHostAndPort, privateKeyBytes, chainBytes);
   mBrowserFrame.nativeSslClientCert(mHandle, privateKeyBytes, chainBytes);
 }
 /**
  * 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);
   }
 }
示例#15
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);
    }
  }
 /** Proceed with the specified private key and client certificate chain. */
 public void proceed(PrivateKey privateKey, X509Certificate[] chain) {
   final byte[] privateKeyBytes = privateKey.getEncoded();
   final byte[][] chainBytes;
   try {
     chainBytes = NativeCrypto.encodeCertificates(chain);
     mTable.Allow(mHostAndPort, privateKeyBytes, chainBytes);
     post(
         new Runnable() {
           public void run() {
             mBrowserFrame.nativeSslClientCert(mHandle, privateKeyBytes, chainBytes);
           }
         });
   } catch (CertificateEncodingException e) {
     post(
         new Runnable() {
           public void run() {
             mBrowserFrame.nativeSslClientCert(mHandle, null, null);
             return;
           }
         });
   }
 }
示例#17
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");
   }
 }
示例#18
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();
   }
 }
示例#19
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;
  }
  /**
   * 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());
  }
示例#21
0
  public static void main(String[] args) {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
      keyGen.initialize(1024, random);

      KeyPair pair = keyGen.generateKeyPair();
      PrivateKey priv = pair.getPrivate();
      PublicKey pub = pair.getPublic();

      byte[] encPriv = priv.getEncoded();
      FileOutputStream privfos = new FileOutputStream("DSAPrivateKey.key");
      privfos.write(encPriv);
      privfos.close();

      byte[] encPub = pub.getEncoded();
      FileOutputStream pubfos = new FileOutputStream("DSAPublicKey.key");
      pubfos.write(encPub);
      pubfos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#22
0
  public void testCompat() throws Exception {
    if (Security.getProvider("SUN") == null) {
      return;
    }

    Signature s = Signature.getInstance("DSA", "SUN");
    KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN");
    byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

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

    KeyPair p = g.generateKeyPair();

    PrivateKey sKey = p.getPrivate();
    PublicKey vKey = p.getPublic();

    //
    // sign SUN - verify with BC
    //
    s.initSign(sKey);

    s.update(data);

    byte[] sigBytes = s.sign();

    s = Signature.getInstance("DSA", "BC");

    s.initVerify(vKey);

    s.update(data);

    if (!s.verify(sigBytes)) {
      fail("SUN -> BC verification failed");
    }

    //
    // sign BC - verify with SUN
    //

    s.initSign(sKey);

    s.update(data);

    sigBytes = s.sign();

    s = Signature.getInstance("DSA", "SUN");

    s.initVerify(vKey);

    s.update(data);

    if (!s.verify(sigBytes)) {
      fail("BC -> SUN verification failed");
    }

    //
    // key encoding test - BC decoding Sun keys
    //
    KeyFactory f = KeyFactory.getInstance("DSA", "BC");
    X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded());

    DSAPublicKey k1 = (DSAPublicKey) f.generatePublic(x509s);

    checkPublic(k1, vKey);

    PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded());

    DSAPrivateKey k2 = (DSAPrivateKey) f.generatePrivate(pkcs8);

    checkPrivateKey(k2, sKey);

    //
    // key decoding test - SUN decoding BC keys
    //
    f = KeyFactory.getInstance("DSA", "SUN");
    x509s = new X509EncodedKeySpec(k1.getEncoded());

    vKey = (DSAPublicKey) f.generatePublic(x509s);

    checkPublic(k1, vKey);

    pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded());
    sKey = f.generatePrivate(pkcs8);

    checkPrivateKey(k2, sKey);
  }
示例#23
0
  public void performTest() throws Exception {
    KeyFactory fact;
    byte[] input =
        new byte[] {
          (byte) 0x54,
          (byte) 0x85,
          (byte) 0x9b,
          (byte) 0x34,
          (byte) 0x2c,
          (byte) 0x49,
          (byte) 0xea,
          (byte) 0x2a
        };
    byte[][] output =
        new byte[][] {
          Hex.decode(
              "8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"),
          Hex.decode(
              "2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"),
          Hex.decode(
              "0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"),
          Hex.decode(
              "1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"),
          Hex.decode(
              "4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"),
          Hex.decode(
              "06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"),
          Hex.decode(
              "135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"),
          Hex.decode(
              "03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"),
          Hex.decode(
              "00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c")
        };
    SecureRandom rand = new FixedSecureRandom();

    fact = KeyFactory.getInstance("RSA", "BC");

    PrivateKey privKey = fact.generatePrivate(privKeySpec);
    PublicKey pubKey = fact.generatePublic(pubKeySpec);

    PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
    PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);

    //
    // key without CRT coefficients
    //
    PrivateKeyInfo keyInfo = PrivateKeyInfo.getInstance(privKey.getEncoded());
    BigInteger zero = BigInteger.valueOf(0);
    PKCS8EncodedKeySpec noCrtSpec =
        new PKCS8EncodedKeySpec(
            new PrivateKeyInfo(
                    keyInfo.getPrivateKeyAlgorithm(),
                    new org.mightyfish.asn1.pkcs.RSAPrivateKey(
                        privKeySpec.getModulus(),
                        privKeySpec.getPublicExponent(),
                        privKeySpec.getPrivateExponent(),
                        zero,
                        zero,
                        zero,
                        zero,
                        zero))
                .getEncoded());

    PrivateKey noCrtKey = fact.generatePrivate(noCrtSpec);
    if (noCrtKey instanceof RSAPrivateCrtKey) {
      fail("private key without CRT coefficients returned as CRT key");
    }

    //
    // No Padding
    //
    Cipher c = Cipher.getInstance("RSA", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    byte[] out = c.doFinal(input);

    if (!areEqual(out, output[0])) {
      fail(
          "NoPadding test failed on encrypt expected "
              + new String(Hex.encode(output[0]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // No Padding - incremental
    //
    c = Cipher.getInstance("RSA", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    c.update(input);

    out = c.doFinal();

    if (!areEqual(out, output[0])) {
      fail(
          "NoPadding test failed on encrypt expected "
              + new String(Hex.encode(output[0]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // No Padding - incremental - explicit use of NONE in mode.
    //
    c = Cipher.getInstance("RSA/NONE/NoPadding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    c.update(input);

    out = c.doFinal();

    if (!areEqual(out, output[0])) {
      fail(
          "NoPadding test failed on encrypt expected "
              + new String(Hex.encode(output[0]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // No Padding - maximum length
    //
    c = Cipher.getInstance("RSA", "BC");

    byte[] modBytes = ((RSAPublicKey) pubKey).getModulus().toByteArray();
    byte[] maxInput = new byte[modBytes.length - 1];

    maxInput[0] |= 0x7f;

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(maxInput);

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, maxInput)) {
      fail(
          "NoPadding test failed on decrypt expected "
              + new String(Hex.encode(maxInput))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // PKCS1 V 1.5
    //
    c = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[1])) {
      fail(
          "PKCS1 test failed on encrypt expected "
              + new String(Hex.encode(output[1]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "PKCS1 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // PKCS1 V 1.5 - NONE
    //
    c = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[1])) {
      fail(
          "PKCS1 test failed on encrypt expected "
              + new String(Hex.encode(output[1]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "PKCS1 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // OAEP - SHA1
    //
    c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[2])) {
      fail(
          "OAEP test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    AlgorithmParameters oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0])))
            .getEncoded())) {
      fail("OAEP test failed default sha-1 parameters");
    }

    //
    // OAEP - SHA224
    //
    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA224AndMGF1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[3])) {
      fail(
          "OAEP SHA-224 test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, priv2048Key);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP SHA-224 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0])))
            .getEncoded())) {
      fail("OAEP test failed default sha-224 parameters");
    }

    //
    // OAEP - SHA 256
    //
    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[4])) {
      fail(
          "OAEP SHA-256 test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, priv2048Key);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP SHA-256 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0])))
            .getEncoded())) {
      fail("OAEP test failed default sha-256 parameters");
    }

    //
    // OAEP - SHA 384
    //
    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA384AndMGF1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[5])) {
      fail(
          "OAEP SHA-384 test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, priv2048Key);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP SHA-384 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0])))
            .getEncoded())) {
      fail("OAEP test failed default sha-384 parameters");
    }

    //
    // OAEP - MD5
    //
    c = Cipher.getInstance("RSA/NONE/OAEPWithMD5AndMGF1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[6])) {
      fail(
          "OAEP MD5 test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP MD5 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0])))
            .getEncoded())) {
      fail("OAEP test failed default md5 parameters");
    }

    //
    // OAEP - SHA1 with default parameters
    //
    c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");

    c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand);

    out = c.doFinal(input);

    if (!areEqual(out, output[2])) {
      fail(
          "OAEP test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    oaepP = c.getParameters();

    if (!areEqual(oaepP.getEncoded(), new byte[] {0x30, 0x00})) {
      fail("OAEP test failed default parameters");
    }

    //
    // OAEP - SHA1 with specified string
    //
    c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");

    c.init(
        Cipher.ENCRYPT_MODE,
        pubKey,
        new OAEPParameterSpec(
            "SHA1",
            "MGF1",
            new MGF1ParameterSpec("SHA1"),
            new PSource.PSpecified(new byte[] {1, 2, 3, 4, 5})),
        rand);

    out = c.doFinal(input);

    oaepP = c.getParameters();

    if (!areEqual(
        oaepP.getEncoded(),
        new RSAESOAEPparams(
                new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_mgf1,
                    new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE)),
                new AlgorithmIdentifier(
                    PKCSObjectIdentifiers.id_pSpecified,
                    new DEROctetString(new byte[] {1, 2, 3, 4, 5})))
            .getEncoded())) {
      fail("OAEP test failed changed sha-1 parameters");
    }

    if (!areEqual(out, output[7])) {
      fail(
          "OAEP test failed on encrypt expected "
              + new String(Hex.encode(output[2]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");

    c.init(Cipher.DECRYPT_MODE, privKey, oaepP);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "OAEP test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // ISO9796-1
    //
    byte[] isoInput =
        Hex.decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
    PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec);
    PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec);

    c = Cipher.getInstance("RSA/NONE/ISO9796-1Padding", "BC");

    c.init(Cipher.ENCRYPT_MODE, isoPrivKey);

    out = c.doFinal(isoInput);

    if (!areEqual(out, output[8])) {
      fail(
          "ISO9796-1 test failed on encrypt expected "
              + new String(Hex.encode(output[3]))
              + " got "
              + new String(Hex.encode(out)));
    }

    c.init(Cipher.DECRYPT_MODE, isoPubKey);

    out = c.doFinal(out);

    if (!areEqual(out, isoInput)) {
      fail(
          "ISO9796-1 test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    //
    // generation with parameters test.
    //
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");

    //
    // 768 bit RSA with e = 2^16-1
    //
    keyPairGen.initialize(
        new RSAKeyGenParameterSpec(768, BigInteger.valueOf(65537)), new SecureRandom());

    KeyPair kp = keyPairGen.generateKeyPair();

    pubKey = kp.getPublic();
    privKey = kp.getPrivate();

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.doFinal(input);

    c.init(Cipher.DECRYPT_MODE, privKey);

    out = c.doFinal(out);

    if (!areEqual(out, input)) {
      fail(
          "key generation test failed on decrypt expected "
              + new String(Hex.encode(input))
              + " got "
              + new String(Hex.encode(out)));
    }

    //
    // comparison check
    //
    KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");

    RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) keyFact.translateKey(privKey);

    if (!privKey.equals(crtKey)) {
      fail("private key equality check failed");
    }

    crtKey =
        (RSAPrivateCrtKey) keyFact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));

    if (!privKey.equals(crtKey)) {
      fail("private key equality check failed");
    }

    crtKey = (RSAPrivateCrtKey) serializeDeserialize(privKey);

    if (!privKey.equals(crtKey)) {
      fail("private key equality check failed");
    }

    if (privKey.hashCode() != crtKey.hashCode()) {
      fail("private key hashCode check failed");
    }

    RSAPublicKey copyKey = (RSAPublicKey) keyFact.translateKey(pubKey);

    if (!pubKey.equals(copyKey)) {
      fail("public key equality check failed");
    }

    copyKey = (RSAPublicKey) keyFact.generatePublic(new X509EncodedKeySpec(pubKey.getEncoded()));

    if (!pubKey.equals(copyKey)) {
      fail("public key equality check failed");
    }

    copyKey = (RSAPublicKey) serializeDeserialize(pubKey);

    if (!pubKey.equals(copyKey)) {
      fail("public key equality check failed");
    }

    if (pubKey.hashCode() != copyKey.hashCode()) {
      fail("public key hashCode check failed");
    }

    //
    // test an OAEP key
    //
    SubjectPublicKeyInfo oaepKey =
        new SubjectPublicKeyInfo(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, new RSAESOAEPparams()),
            SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).parsePublicKey());

    copyKey =
        (RSAPublicKey)
            serializeDeserialize(
                keyFact.generatePublic(new X509EncodedKeySpec(oaepKey.getEncoded())));

    if (!pubKey.equals(copyKey)) {
      fail("public key equality check failed");
    }

    if (pubKey.hashCode() != copyKey.hashCode()) {
      fail("public key hashCode check failed");
    }

    if (!Arrays.areEqual(copyKey.getEncoded(), oaepKey.getEncoded())) {
      fail("encoding does not match");
    }

    oaepCompatibilityTest("SHA-1", priv2048Key, pub2048Key);
    // TODO: oaepCompatibilityTest("SHA-224", priv2048Key, pub2048Key);      commented out as fails
    // in JDK 1.7
    oaepCompatibilityTest("SHA-256", priv2048Key, pub2048Key);
    oaepCompatibilityTest("SHA-384", priv2048Key, pub2048Key);
    oaepCompatibilityTest("SHA-512", priv2048Key, pub2048Key);

    SecureRandom random = new SecureRandom();
    rawModeTest("SHA1withRSA", X509ObjectIdentifiers.id_SHA1, priv2048Key, pub2048Key, random);
    rawModeTest("MD5withRSA", PKCSObjectIdentifiers.md5, priv2048Key, pub2048Key, random);
    rawModeTest(
        "RIPEMD128withRSA", TeleTrusTObjectIdentifiers.ripemd128, priv2048Key, pub2048Key, random);

    // init reset test
    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.update(new byte[40]);

    c.init(Cipher.ENCRYPT_MODE, pubKey, rand);

    out = c.update(new byte[40]);
  }
 /**
  * Returns the encoded data corresponding to a given PrivateKey. Note that this will fail for
  * platform keys on Android 4.0.4 and higher. It can be used on 4.0.3 and older platforms to route
  * around the platform bug described below.
  *
  * @param key A PrivateKey instance
  * @return encoded key as PKCS#8 byte array, can be null.
  */
 @CalledByNative
 public static byte[] getPrivateKeyEncodedBytes(PrivateKey key) {
   return key.getEncoded();
 }
示例#25
0
 /**
  * Add Operator Keys
  *
  * @param privKey
  * @param pubKey
  */
 public void addKeys(PrivateKey privKey, PublicKey pubKey) {
   this.setPublicKey(SecurityData.encode64(pubKey.getEncoded()));
   this.setPrivateKey(SecurityData.encode64(privKey.getEncoded()));
 }
示例#26
0
 public static String getPrivateKey(KeyPair keyPair) {
   PrivateKey pub = keyPair.getPrivate();
   return getHexString(pub.getEncoded());
 }