Exemplo n.º 1
0
  protected void engineInit(Key key, AlgorithmParameterSpec params)
      throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;

    if (key == null) {
      throw new InvalidKeyException("key is null");
    }

    if (key instanceof JCEPBEKey) {
      JCEPBEKey k = (JCEPBEKey) key;

      if (k.getParam() != null) {
        param = k.getParam();
      } else if (params instanceof PBEParameterSpec) {
        param = PBE.Util.makePBEMacParameters(k, params);
      } else {
        throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
      }
    } else if (params instanceof IvParameterSpec) {
      param =
          new ParametersWithIV(
              new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV());
    } else if (params == null) {
      param = new KeyParameter(key.getEncoded());
    } else {
      throw new InvalidAlgorithmParameterException("unknown parameter type.");
    }

    macEngine.init(param);
  }
Exemplo n.º 2
0
  /** 生成密钥对 */
  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;
  }
Exemplo n.º 3
0
 private static BufferedBlockCipher func_75892_a(boolean par0, Key par1Key) {
   BufferedBlockCipher var2 = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
   var2.init(
       par0,
       new ParametersWithIV(new KeyParameter(par1Key.getEncoded()), par1Key.getEncoded(), 0, 16));
   return var2;
 }
  /**
   * Converts, if possible, a given key into a key specification. Currently, the following key
   * specifications are supported:
   *
   * <ul>
   *   <li>for McElieceCCA2PublicKey: {@link X509EncodedKeySpec}, {@link McElieceCCA2PublicKeySpec}
   *   <li>for McElieceCCA2PrivateKey: {@link PKCS8EncodedKeySpec}, {@link
   *       McElieceCCA2PrivateKeySpec}.
   * </ul>
   *
   * @param key the key
   * @param keySpec the key specification
   * @return the specification of the McEliece CCA2 key
   * @throws InvalidKeySpecException if the key type or the key specification is not supported.
   * @see BCMcElieceCCA2PrivateKey
   * @see McElieceCCA2PrivateKeySpec
   * @see BCMcElieceCCA2PublicKey
   * @see McElieceCCA2PublicKeySpec
   */
  public KeySpec getKeySpec(Key key, Class keySpec) throws InvalidKeySpecException {
    if (key instanceof BCMcElieceCCA2PrivateKey) {
      if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) {
        return new PKCS8EncodedKeySpec(key.getEncoded());
      } else if (McElieceCCA2PrivateKeySpec.class.isAssignableFrom(keySpec)) {
        BCMcElieceCCA2PrivateKey privKey = (BCMcElieceCCA2PrivateKey) key;
        return new McElieceCCA2PrivateKeySpec(
            OID,
            privKey.getN(),
            privKey.getK(),
            privKey.getField(),
            privKey.getGoppaPoly(),
            privKey.getP(),
            privKey.getH(),
            privKey.getQInv());
      }
    } else if (key instanceof BCMcElieceCCA2PublicKey) {
      if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) {
        return new X509EncodedKeySpec(key.getEncoded());
      } else if (McElieceCCA2PublicKeySpec.class.isAssignableFrom(keySpec)) {
        BCMcElieceCCA2PublicKey pubKey = (BCMcElieceCCA2PublicKey) key;
        return new McElieceCCA2PublicKeySpec(OID, pubKey.getN(), pubKey.getT(), pubKey.getG());
      }
    } else {
      throw new InvalidKeySpecException("Unsupported key type: " + key.getClass() + ".");
    }

    throw new InvalidKeySpecException("Unknown key specification: " + keySpec + ".");
  }
Exemplo n.º 5
0
 public static BufferedBlockCipher getCipher(boolean forEncryption, Key shared) {
   BufferedBlockCipher cip = new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
   cip.init(
       forEncryption,
       new ParametersWithIV(new KeyParameter(shared.getEncoded()), shared.getEncoded(), 0, 16));
   return cip;
 }
Exemplo n.º 6
0
  /**
   * This method returns a specification for the supplied key.
   *
   * <p>The specification will be returned in the form of an object of the type specified by
   * keySpec.
   *
   * @param key - either DSAPrivateKey or DSAPublicKey
   * @param keySpec - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class
   * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec
   * @throws InvalidKeySpecException if "keySpec" is not a specification for DSAPublicKey or
   *     DSAPrivateKey
   */
  protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
      throws InvalidKeySpecException {

    BigInteger p, q, g, x, y;

    if (key != null) {
      if (keySpec == null) {
        throw new NullPointerException("keySpec == null");
      }
      if (key instanceof DSAPrivateKey) {
        DSAPrivateKey privateKey = (DSAPrivateKey) key;

        if (keySpec.equals(DSAPrivateKeySpec.class)) {

          x = privateKey.getX();

          DSAParams params = privateKey.getParams();

          p = params.getP();
          q = params.getQ();
          g = params.getG();

          return (T) (new DSAPrivateKeySpec(x, p, q, g));
        }

        if (keySpec.equals(PKCS8EncodedKeySpec.class)) {
          return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
        }

        throw new InvalidKeySpecException(
            "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec");
      }

      if (key instanceof DSAPublicKey) {
        DSAPublicKey publicKey = (DSAPublicKey) key;

        if (keySpec.equals(DSAPublicKeySpec.class)) {

          y = publicKey.getY();

          DSAParams params = publicKey.getParams();

          p = params.getP();
          q = params.getQ();
          g = params.getG();

          return (T) (new DSAPublicKeySpec(y, p, q, g));
        }

        if (keySpec.equals(X509EncodedKeySpec.class)) {
          return (T) (new X509EncodedKeySpec(key.getEncoded()));
        }

        throw new InvalidKeySpecException(
            "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec");
      }
    }
    throw new InvalidKeySpecException("'key' is neither DSAPublicKey nor DSAPrivateKey");
  }
Exemplo n.º 7
0
  public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {

    Key key = (Key) keyMap.get(PRIVATE_KEY);

    byte[] privateKey = key.getEncoded();

    return encryptBASE64(key.getEncoded());
  }
  /**
   * This method returns a specification for the supplied key.
   *
   * <p>The specification will be returned in the form of an object of the type specified by
   * keySpec.
   *
   * @param key - either DSAPrivateKey or DSAPublicKey
   * @param keySpec - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class
   * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec
   * @throws InvalidKeySpecException if "keySpec" is not a specification for DSAPublicKey or
   *     DSAPrivateKey
   */
  protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
      throws InvalidKeySpecException {

    BigInteger p, q, g, x, y;

    if (key != null) {
      if (keySpec == null) {
        throw new NullPointerException(Messages.getString("security.19E")); // $NON-NLS-1$
      }
      if (key instanceof DSAPrivateKey) {
        DSAPrivateKey privateKey = (DSAPrivateKey) key;

        if (keySpec.equals(DSAPrivateKeySpec.class)) {

          x = privateKey.getX();

          DSAParams params = privateKey.getParams();

          p = params.getP();
          q = params.getQ();
          g = params.getG();

          return (T) (new DSAPrivateKeySpec(x, p, q, g));
        }

        if (keySpec.equals(PKCS8EncodedKeySpec.class)) {
          return (T) (new PKCS8EncodedKeySpec(key.getEncoded()));
        }

        throw new InvalidKeySpecException(Messages.getString("security.19C")); // $NON-NLS-1$
      }

      if (key instanceof DSAPublicKey) {
        DSAPublicKey publicKey = (DSAPublicKey) key;

        if (keySpec.equals(DSAPublicKeySpec.class)) {

          y = publicKey.getY();

          DSAParams params = publicKey.getParams();

          p = params.getP();
          q = params.getQ();
          g = params.getG();

          return (T) (new DSAPublicKeySpec(y, p, q, g));
        }

        if (keySpec.equals(X509EncodedKeySpec.class)) {
          return (T) (new X509EncodedKeySpec(key.getEncoded()));
        }

        throw new InvalidKeySpecException(Messages.getString("security.19D")); // $NON-NLS-1$
      }
    }
    throw new InvalidKeySpecException(Messages.getString("security.19F")); // $NON-NLS-1$
  }
Exemplo n.º 9
0
 private static BufferedBlockCipher func_75892_a(boolean p_75892_0_, Key p_75892_1_) {
   BufferedBlockCipher bufferedblockcipher =
       new BufferedBlockCipher(new CFBBlockCipher(new AESFastEngine(), 8));
   bufferedblockcipher.init(
       p_75892_0_,
       new ParametersWithIV(
           new KeyParameter(p_75892_1_.getEncoded()), p_75892_1_.getEncoded(), 0, 16));
   return bufferedblockcipher;
 }
  public boolean shareAESkey() {
    try {
      Envelope message = null, e = null;

      // Generate AES key
      KeyGenerator keyGen = KeyGenerator.getInstance("AES");
      AESkey = keyGen.generateKey();
      keyGen = KeyGenerator.getInstance("HmacSHA1");
      HMACkey = keyGen.generateKey();
      byte[] keyBytes = AESkey.getEncoded();
      byte[] hashBytes = HMACkey.getEncoded();
      System.out.println("AES key generated");
      System.out.println("HMAC key generated");
      System.out.println("Begin Encryption...");
      // Encrypt message  w/ provided public key
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

      cipher.init(Cipher.ENCRYPT_MODE, pubKey);
      byte[] cipherBytes = cipher.doFinal(keyBytes);
      byte[] cipherBytes1 = cipher.doFinal(hashBytes);
      System.out.println("Encryption Complete");

      message = new Envelope("SKEY");
      message.addObject(cipherBytes); // Add AESkey to message
      message.addObject(cipherBytes1);
      message.addObject(nonce);
      nonce++;

      byte[] messageBytes = Envelope.toByteArray(message);

      output.writeObject(messageBytes);

      byte[] inCipherBytes = (byte[]) input.readObject();

      // Decrypt response
      cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, AESkey);
      byte[] responseBytes = cipher.doFinal(inCipherBytes);

      Envelope response = Envelope.getEnvelopefromBytes(responseBytes);

      // If server indicates success, return the member list
      if (response.getMessage().equals("OK")
          && (Integer) response.getObjContents().get(0) == nonce) {
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace(System.err);
      return false;
    }
  }
Exemplo n.º 11
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");
   }
 }
Exemplo n.º 12
0
 /**
  * Convert a Key to string encoded as BASE64
  *
  * @param key The key (private or public)
  * @return A string representation of the key
  */
 public static String getKeyAsString(Key key) {
   // Get the bytes of the key
   byte[] keyBytes = key.getEncoded();
   // Convert key to BASE64 encoded string
   BASE64Encoder b64 = new BASE64Encoder();
   return b64.encode(keyBytes);
 }
Exemplo n.º 13
0
 /**
  * Returns the key size of the given key object.
  *
  * @param key the key object.
  * @return the key size of the given key object.
  * @exception InvalidKeyException if <code>key</code> is invalid.
  */
 protected int engineGetKeySize(Key key) throws InvalidKeyException {
   byte[] encoded = key.getEncoded();
   if (encoded.length != 8) {
     throw new InvalidKeyException("Invalid key length: " + encoded.length + " bytes");
   }
   return 56;
 }
  @Override
  public String toString() {
    if (null == _nodeKey) {
      return "NodeKey for node: "
          + _nodeName
          + " Stored at: "
          + _storedNodeKeyName
          + " Stored ID: "
          + DataUtils.printHexBytes(_storedNodeKeyID)
          + " Key: null"
          + " Key id: null";
    }

    // not great to print out keys, but nec for debugging
    return "NodeKey for node: "
        + _nodeName
        + " Stored at: "
        + _storedNodeKeyName
        + " Stored ID: "
        + DataUtils.printHexBytes(_storedNodeKeyID)
        + " Key: "
        + DataUtils.printHexBytes(_nodeKey.getEncoded())
        + " Key id: "
        + DataUtils.printHexBytes(WrappedKey.wrappingKeyIdentifier(_nodeKey));
  }
Exemplo n.º 15
0
  public String createKey() throws NoSuchAlgorithmException, NoSuchProviderException {

    KeyGenerator keygen = KeyGenerator.getInstance("AES", "BC");
    keygen.init(256);
    Key key = keygen.generateKey();

    return Base64.encodeBase64String(key.getEncoded());
  }
 @Override
 public void storeKey(Key key) throws KeyStoringException {
   Path keyPath = FileSystemService.getUserRapidMinerDir().toPath().resolve(DEFAULTKEY_FILE_NAME);
   try {
     KeyGeneratorTool.storeKey(key.getEncoded(), keyPath);
   } catch (IOException e) {
     throw new KeyStoringException("Could not store new cipher key", e);
   }
 }
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((_nodeKey == null) ? 0 : Arrays.hashCode(_nodeKey.getEncoded()));
   result = prime * result + ((_nodeName == null) ? 0 : _nodeName.hashCode());
   result = prime * result + Arrays.hashCode(_storedNodeKeyID);
   result = prime * result + ((_storedNodeKeyName == null) ? 0 : _storedNodeKeyName.hashCode());
   return result;
 }
 @Override
 protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
   try {
     byte[] encoded = key.getEncoded();
     return engineDoFinal(encoded, 0, encoded.length);
   } catch (BadPaddingException e) {
     IllegalBlockSizeException newE = new IllegalBlockSizeException();
     newE.initCause(e);
     throw newE;
   }
 }
Exemplo n.º 19
0
 /**
  * 张纪豪添加
  *
  * @param len
  * @param password
  * @return
  */
 public static String generateKey(int len, String password) {
   try {
     KeyGenerator keyGen = KeyGenerator.getInstance("AES");
     keyGen.init(len);
     keyGen.init(128, new SecureRandom(password.getBytes()));
     Key key = keyGen.generateKey();
     return Strings.toHexString(key.getEncoded());
   } catch (Exception e) {
     return null;
   }
 }
Exemplo n.º 20
0
 public static String generateKey(int len) {
   try {
     KeyGenerator keyGen = KeyGenerator.getInstance("AES");
     keyGen.init(len);
     Key key = keyGen.generateKey();
     // System.out.println(key.getEncoded());
     return Strings.toHexString(key.getEncoded());
   } catch (Exception e) {
     return null;
   }
 }
Exemplo n.º 21
0
 protected void engineInit(
     int paramInt,
     Key paramKey,
     AlgorithmParameterSpec paramAlgorithmParameterSpec,
     SecureRandom paramSecureRandom) {
   Object localObject;
   if ((paramKey instanceof BCPBEKey)) {
     paramKey = (BCPBEKey) paramKey;
     if ((paramAlgorithmParameterSpec instanceof PBEParameterSpec)) {
       localObject = PBE.Util.ˊ(paramKey, paramAlgorithmParameterSpec, this.aXL.iG());
     } else if (paramKey.nU() != null) {
       localObject = paramKey.nU();
     } else {
       throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
     }
   } else {
     localObject = new KeyParameter(paramKey.getEncoded());
   }
   paramKey = (Key) localObject;
   if ((paramAlgorithmParameterSpec instanceof IvParameterSpec)) {
     paramKey =
         new ParametersWithIV(
             (CipherParameters) localObject,
             ((IvParameterSpec) paramAlgorithmParameterSpec).getIV());
   }
   paramAlgorithmParameterSpec = paramKey;
   if ((paramKey instanceof KeyParameter)) {
     paramAlgorithmParameterSpec = paramKey;
     if (this.aYU != 0) {
       this.iv = new byte[this.aYU];
       paramSecureRandom.nextBytes(this.iv);
       paramAlgorithmParameterSpec = new ParametersWithIV(paramKey, this.iv);
     }
   }
   paramKey = paramAlgorithmParameterSpec;
   if (paramSecureRandom != null) {
     paramKey = new ParametersWithRandom(paramAlgorithmParameterSpec, paramSecureRandom);
   }
   switch (paramInt) {
     default:
       break;
     case 3:
       this.aXL.ˊ(true, paramKey);
       return;
     case 4:
       this.aXL.ˊ(false, paramKey);
       return;
     case 1:
     case 2:
       throw new IllegalArgumentException("engine only valid for wrapping");
   }
   System.out.println("eeek!");
 }
Exemplo n.º 22
0
  /**
   * Wrapping allows to mask/encapsulate/protect the key used Create another key, use a cipher with
   * it and {@link Cipher#WRAP_MODE} and wrap the original key To unwrap, use a cipher with {@link
   * Cipher#UNWRAP_MODE}
   */
  static void wrapUnwrapKey() throws Exception {
    // create a key to wrap
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128);
    Key keyToBeWrapped = generator.generateKey();
    System.out.println("input    : " + Utils.toHex(keyToBeWrapped.getEncoded()));

    // create a wrapper and do the wrapping
    Cipher cipher = Cipher.getInstance("AESWrap");
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    Key wrapKey = keyGenerator.generateKey();
    cipher.init(Cipher.WRAP_MODE, wrapKey);
    byte[] wrappedKey = cipher.wrap(keyToBeWrapped);
    System.out.println("wrapped : " + Utils.toHex(wrappedKey));

    // unwrap the wrapped key
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
    System.out.println("unwrapped: " + Utils.toHex(key.getEncoded()));
  }
Exemplo n.º 23
0
  protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
    byte[] encoded = key.getEncoded();
    if (encoded == null) {
      throw new InvalidKeyException("Cannot wrap key, null encoding.");
    }

    try {
      return engineDoFinal(encoded, 0, encoded.length);
    } catch (BadPaddingException e) {
      throw new IllegalBlockSizeException(e.getMessage());
    }
  }
Exemplo n.º 24
0
 @Test(timeout = 30000)
 public void testKeyStoreKeyProviderWithPassword() throws Exception {
   KeyProvider provider = new KeyStoreKeyProvider();
   provider.init("jceks://" + storeFile.toURI().getPath() + "?password=" + PASSWORD);
   Key key = provider.getKey(ALIAS);
   assertNotNull(key);
   byte[] keyBytes = key.getEncoded();
   assertEquals(keyBytes.length, KEY.length);
   for (int i = 0; i < KEY.length; i++) {
     assertEquals(keyBytes[i], KEY[i]);
   }
 }
Exemplo n.º 25
0
 public static byte[] genarateRandomKey() {
   KeyGenerator keygen = null;
   try {
     keygen = KeyGenerator.getInstance(ConfigureEncryptAndDecrypt.AES_ALGORITHM);
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(" genarateRandomKey fail!", e);
   }
   SecureRandom random = new SecureRandom();
   keygen.init(random);
   Key key = keygen.generateKey();
   return key.getEncoded();
 }
Exemplo n.º 26
0
  @Kroll.method
  public KrollDict generateKeyPair() {
    // generate key pair
    //
    KrollDict arg = new KrollDict();

    try {
      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
      kpg.initialize(1024);
      KeyPair kp = kpg.genKeyPair();
      publicKey = kp.getPublic();
      privateKey = kp.getPrivate();

      arg.put("privateKey", Base64.encodeToString(privateKey.getEncoded(), Base64.NO_WRAP));
      arg.put("publicKey", Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP));

    } catch (Exception e) {
      Log.e(TAG, "RSA key pair error");
    }

    return arg;
  }
Exemplo n.º 27
0
  /**
   * Encrypt the MAC key using the provided shared secret.
   *
   * @param macKey MAC key to encrypt
   * @param sharedSecret shared secret used to encrypt MAC key
   * @return encrypted MAC Key
   */
  private static SecretKey macKeyEncryption(Key macKey, SecretKey sharedSecret) {
    try {
      MessageDigest messageDigest = MessageDigest.getInstance(sharedSecret.getAlgorithm());
      byte[] digestedSecret = messageDigest.digest(sharedSecret.getEncoded());

      byte[] encrypted = xor(macKey.getEncoded(), digestedSecret);
      return new SecretKeySpec(encrypted, macKey.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
      log.error("unable to encrypt MAC key: {}", e.getMessage());
    }

    return null;
  }
Exemplo n.º 28
0
  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);
  }
Exemplo n.º 29
0
  byte[] getPublicKeyEncoded() {
    try {
      // generate a key pair
      SecureRandom random = new SecureRandom();
      KeyPairGenerator generator = KeyPairGenerator.getInstance(ASYM_KEY_TYPE);
      generator.initialize(ASYM_KEY_SIZE, random);

      _serverKeyPair = generator.generateKeyPair();
      Key pubKey = _serverKeyPair.getPublic();
      return pubKey.getEncoded();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Exemplo n.º 30
0
 /** Test that key1 (reference key) and key2 (key to be tested) are equivalent */
 private static void testKey(Key key1, Key key2) throws Exception {
   if (key2.getAlgorithm().equals("EC") == false) {
     throw new Exception("Algorithm not EC");
   }
   if (key1 instanceof PublicKey) {
     if (key2.getFormat().equals("X.509") == false) {
       throw new Exception("Format not X.509");
     }
   } else if (key1 instanceof PrivateKey) {
     if (key2.getFormat().equals("PKCS#8") == false) {
       throw new Exception("Format not PKCS#8");
     }
   }
   if (key1.equals(key2) == false) {
     System.out.println("key1: " + key1);
     System.out.println("key2: " + key2);
     System.out.println("enc1: " + toString(key1.getEncoded()));
     System.out.println("enc2: " + toString(key2.getEncoded()));
     throw new Exception("Keys not equal");
   }
   if (Arrays.equals(key1.getEncoded(), key2.getEncoded()) == false) {
     throw new Exception("Encodings not equal");
   }
 }