Esempio n. 1
0
 /**
  * 加密
  *
  * @param content 需要加密的内容
  * @param password 加密密码
  * @return
  */
 public static byte[] encryptAES(String content, String password) {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(password.getBytes()));
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, key); // 初始化
     byte[] result = cipher.doFinal(byteContent);
     return result; // 加密
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 2
0
  private Object findByPrimaryKey(
      final Method callMethod,
      final Object[] args,
      final ThreadContext callContext,
      final InterfaceType interfaceType)
      throws OpenEJBException {
    final BeanContext beanContext = callContext.getBeanContext();

    final TransactionPolicy txPolicy =
        createTransactionPolicy(
            beanContext.getTransactionType(callMethod, interfaceType), callContext);

    try {
      final EntityBean bean = (EntityBean) cmpEngine.loadBean(callContext, args[0]);
      if (bean == null) {
        throw new ObjectNotFoundException(beanContext.getDeploymentID() + " : " + args[0]);
      }

      // rebuild the primary key
      final KeyGenerator kg = beanContext.getKeyGenerator();
      final Object primaryKey = kg.getPrimaryKey(bean);

      // create a new ProxyInfo based on the deployment info and primary key
      return new ProxyInfo(beanContext, primaryKey);
    } catch (final FinderException fe) {
      handleApplicationException(txPolicy, fe, false);
    } catch (final Throwable e) { // handle reflection exception
      handleSystemException(txPolicy, e, callContext);
    } finally {
      afterInvoke(txPolicy, callContext);
    }
    throw new AssertionError("Should not get here");
  }
 public static void main(String[] args) throws Exception {
   //
   // check args and get plaintext
   if (args.length != 1) {
     System.err.println("Usage: java MessageAuthenticationCodeExample text");
     System.exit(1);
   }
   byte[] plainText = args[0].getBytes("UTF8");
   //
   // get a key for the HmacMD5 algorithm
   System.out.println("\nStart generating key");
   KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
   SecretKey MD5key = keyGen.generateKey();
   System.out.println("Finish generating key");
   //
   // get a MAC object and update it with the plaintext
   Mac mac = Mac.getInstance("HmacMD5");
   mac.init(MD5key);
   mac.update(plainText);
   //
   // print out the provider used and the MAC
   System.out.println("\n" + mac.getProvider().getInfo());
   System.out.println("\nMAC: ");
   System.out.println(new String(mac.doFinal(), "UTF8"));
 }
Esempio n. 4
0
  public void testKeyGen() {
    RandomSource.getInstance().nextBoolean();
    byte src[] = new byte[200];
    RandomSource.getInstance().nextBytes(src);

    I2PAppContext ctx = I2PAppContext.getGlobalContext();
    for (int i = 0; i < 10; i++) {
      Object keys[] = KeyGenerator.getInstance().generatePKIKeypair();
      byte ctext[] = ctx.elGamalEngine().encrypt(src, (PublicKey) keys[0]);
      byte ptext[] = ctx.elGamalEngine().decrypt(ctext, (PrivateKey) keys[1]);
      assertTrue(DataHelper.eq(ptext, src));
    }

    Object obj[] = KeyGenerator.getInstance().generateSigningKeypair();
    SigningPublicKey fake = (SigningPublicKey) obj[0];
    for (int i = 0; i < 10; i++) {
      Object keys[] = KeyGenerator.getInstance().generateSigningKeypair();

      Signature sig = DSAEngine.getInstance().sign(src, (SigningPrivateKey) keys[1]);
      assertTrue(DSAEngine.getInstance().verifySignature(sig, src, (SigningPublicKey) keys[0]));
      assertFalse(DSAEngine.getInstance().verifySignature(sig, src, fake));
    }

    for (int i = 0; i < 1000; i++) {
      KeyGenerator.getInstance().generateSessionKey();
    }
  }
Esempio n. 5
0
  private static byte[] doAes(int mode, byte[] input, String password) {
    try {
      KeyGenerator keygen = KeyGenerator.getInstance(AES_ALGORITHM_NAME);
      keygen.init(128, new SecureRandom(password.getBytes()));
      SecretKey secretKey = keygen.generateKey();

      byte[] enCodeFormat = secretKey.getEncoded();
      SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES_ALGORITHM_NAME);

      Cipher cipher = Cipher.getInstance(AES_ALGORITHM_NAME);
      cipher.init(Cipher.DECRYPT_MODE, key);

      return cipher.doFinal(input);
    } 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();
    }
    return null;
  }
  private static SecretKey generateSymmetricKey() throws Exception {
    KeyGenerator generator = KeyGenerator.getInstance(KEY_ALGORITHM);
    SecureRandom random = new SecureRandom();
    generator.init(KEY_LENGTH_BITS, random);
    logger.debug("Generate Key");
    return generator.generateKey();
    // return new SecretKeySpec(Hex.decodeHex("cb024600dce7148b8ddc5d6c111fbd85".toCharArray()),
    // KEY_ALGORITHM);

  }
Esempio n. 7
0
  private ThreadContext createThreadContext(final EntityBean entityBean) {
    if (entityBean == null) {
      throw new NullPointerException("entityBean is null");
    }

    final BeanContext beanContext = getBeanContextByClass(entityBean.getClass());
    final KeyGenerator keyGenerator = beanContext.getKeyGenerator();
    final Object primaryKey = keyGenerator.getPrimaryKey(entityBean);

    return new ThreadContext(beanContext, primaryKey);
  }
  public void inicializarSeguridad() {
    // Generar la llave
    try {
      KeyGenerator keygen = KeyGenerator.getInstance("DES");
      desKey = keygen.generateKey();
      // Iniciar un objeto para la encr / desencr
      desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    } catch (Exception e) {

    }
  }
Esempio n. 9
0
 @Override
 public SymmetricKey createKey() {
   KeyGenerator kgen;
   try {
     kgen = KeyGenerator.getInstance("AES");
     kgen.init(256);
     final SecretKey skey = kgen.generateKey();
     return new AES256SymmetricKey(skey.getEncoded());
   } catch (final NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   }
 }
Esempio n. 10
0
  public static void main(String[] args) {
    KeyGenerator keyGen = getKeyGenerator();

    for (int i = 0; i < 10; i++) {
      try {
        long key = keyGen.getKey();
        System.out.println("Key: " + key);
      } catch (SecurityException ex) {
        System.out.println("취약한 키가 생성되었습니다.");
      }
    }
  }
Esempio n. 11
0
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // get user inputted key
    byte[] userkey = null;
    do {
      System.out.println("Please enter a 8 character string to generate a Secret Key");
      userkey = (in.readLine()).getBytes();
    } while (userkey.length != 8);

    // create Key Generator instance and generate a secret key
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecretKey skey = kgen.generateKey();

    byte[] key = userkey;
    // Create a Secret Key based on characters entered by the user
    SecretKeySpec skeyspec = new SecretKeySpec(key, "DES");

    // Create a cipher to encrypt with
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeyspec);

    // Get message
    System.out.println("Please enter a string to encrypt");
    byte[] userstring = null;
    userstring = (in.readLine()).getBytes();

    // Encrypt message with cipher
    byte[] encrypted = cipher.doFinal(userstring);
    String enc_string = new String(encrypted);
    System.out.println("The String is encrypted as " + enc_string);

    byte[] userdecrypt = null;
    byte[] decrypted = null;

    // Get user decrypt key
    do {
      System.out.println("Please enter the 8 character key to decrypt the message");
      userdecrypt = (in.readLine()).getBytes();
    } while (userdecrypt.length != 8);

    // Reinitialize Secret Key and Cipher
    key = userdecrypt;
    SecretKeySpec decryptkey = new SecretKeySpec(key, "DES");
    cipher.init(Cipher.DECRYPT_MODE, decryptkey);

    // Decrypt message
    decrypted = cipher.doFinal(encrypted);

    if ((new String(decrypted)).equals(new String(userstring)))
      System.out.println("\nMessage decrypted as: " + (new String(decrypted)));
    else System.out.println("\nMessage was not decrypted");
  }
  public void generate_new_aes_key() {

    try {
      KeyGenerator localKeyGenerator = KeyGenerator.getInstance("AES");
      localKeyGenerator.init(128, SecureRandom.getInstance("SHA1PRNG"));
      //        aes_key = Base64.encodeBase64String(localKeyGenerator.generateKey().getEncoded());
      aes_key =
          new String(Base64.encode(localKeyGenerator.generateKey().getEncoded(), Base64.DEFAULT));
    } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
      System.out.println(localNoSuchAlgorithmException);
    }
    return;
  }
Esempio n. 13
0
 /**
  * Generates a random secret key using the algorithm specified in the first DataReference URI
  *
  * @param dataRefURIs
  * @param doc
  * @param wsDocInfo
  * @return
  * @throws WSSecurityException
  */
 private static byte[] getRandomKey(List<String> dataRefURIs, Document doc, WSDocInfo wsDocInfo)
     throws WSSecurityException {
   try {
     String alg = "AES";
     int size = 16;
     if (!dataRefURIs.isEmpty()) {
       String uri = dataRefURIs.iterator().next();
       Element ee = ReferenceListProcessor.findEncryptedDataElement(doc, uri);
       String algorithmURI = X509Util.getEncAlgo(ee);
       alg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
       size = WSSecurityUtil.getKeyLength(algorithmURI);
     }
     KeyGenerator kgen = KeyGenerator.getInstance(alg);
     kgen.init(size * 8);
     SecretKey k = kgen.generateKey();
     return k.getEncoded();
   } catch (Throwable ex) {
     // Fallback to just using AES to avoid attacks on EncryptedData algorithms
     try {
       KeyGenerator kgen = KeyGenerator.getInstance("AES");
       kgen.init(128);
       SecretKey k = kgen.generateKey();
       return k.getEncoded();
     } catch (NoSuchAlgorithmException e) {
       throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
     }
   }
 }
Esempio n. 14
0
  /* ------------------------------------------------------------------ */
  public void propertyChange(PropertyChangeEvent aEvent) throws com.sun.star.uno.RuntimeException {
    try {
      // did it come from a radio button or checkbox?
      if (aEvent.PropertyName.equals("State")) { // yep
        Short aNewState = (Short) aEvent.NewValue;

        XPropertySet xModel = UNO.queryPropertySet(aEvent.Source);
        String sName = (String) xModel.getPropertyValue("Name");

        Short aClassId = (Short) xModel.getPropertyValue("ClassId");
        if (FormComponentType.RADIOBUTTON == aClassId.shortValue()) {
          String sRefValue = (String) xModel.getPropertyValue("RefValue");

          short nNewValue = ((Short) aEvent.NewValue).shortValue();
          if (sName.equals("KeyGen")) {
            // it's one of the options for key generation
            if (sRefValue.equals("none")) { // no automatic generation at all
              m_aSalesmanKeyGenerator.stopGenerator();
              m_aSalesKeyGenerator.stopGenerator();
            } else {
              boolean bGenerateOnReset = true;
              if (sRefValue.equals("update")) { // generate on update
                bGenerateOnReset = (0 == nNewValue);
              } else if (sRefValue.equals("reset")) { // generate on reset
                bGenerateOnReset = (0 != nNewValue);
              }
              m_aSalesmanKeyGenerator.activateKeyGenerator(bGenerateOnReset);
              m_aSalesKeyGenerator.activateKeyGenerator(bGenerateOnReset);
            }
          }
        } else if (FormComponentType.CHECKBOX == aClassId.shortValue()) {
          boolean bEnabled = (0 != aNewState.shortValue());
          if (sName.equals("defaultdate")) {
            m_bDefaultSalesDate = bEnabled;
          } else if (sName.equals("protectkeys")) {
            m_bProtectKeyFields = bEnabled;
            m_aSalesmenLocker.enableLock(m_bProtectKeyFields);
            m_aSalesLocker.enableLock(m_bProtectKeyFields);
          } else if (sName.equals("emptysales")) {
            m_bAllowEmptySales = bEnabled;
            m_aSalesNameValidator.enableColumnWatch(m_bAllowEmptySales);
          }
        }
      }
    } catch (com.sun.star.uno.Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
  private void setKeyProperties(DataObject data, final DataObject associatedObject)
      throws Exception {

    s_log.info("setting key properties");
    KeyGenerator.setKeyValues(data);

    final ObjectType type = data.getObjectType();
    PropertyManipulator.AttributeManipulator manip =
        new PropertyManipulator.AttributeManipulator() {
          public boolean obeys(Property p) {
            return super.obeys(p) && type.isKeyProperty(p) && p.getType().isCompound();
          }

          public void manipulate(Property p, DataObject dataInner) throws Exception {
            if (associatedObject != null && p.getType().equals(associatedObject.getObjectType())) {

              dataInner.set(p.getName(), associatedObject);
            } else {
              DataObject object =
                  SessionManager.getSession().create(p.getType().getQualifiedName());
              reportPropertyTypes(object);
              initializeObject(object, dataInner);
            }
          }
        };
    PropertyManipulator.manipulateProperties(data, manip);
  }
  private void setDefaultProperties(DataObject data, DataObject associatedObject) throws Exception {

    final ObjectType type = data.getObjectType();
    s_log.info("");
    s_log.info("Making new object for: " + type.getQualifiedName());
    KeyGenerator.setKeyValues(data);

    ObjectType associated = (associatedObject == null) ? null : associatedObject.getObjectType();

    for (Iterator it = type.getKeyProperties(); it.hasNext(); ) {
      Property prop = (Property) it.next();
      if (prop.isAttribute()) {
        continue;
      }

      DataType propType = prop.getType();
      if (propType.equals(associated)) {
        data.set(prop.getName(), associatedObject);
      } else {
        makeChild(prop, data);
      }
    }

    PropertyManipulator.NonKeyManipulator manip =
        new PropertyManipulator.NonKeyManipulator(type) {
          public void manipulate(Property p, DataObject dataInner) throws Exception {
            m_manipulator.setDefaultProperty(p, dataInner);
          }
        };

    PropertyManipulator.manipulateProperties(data, manip);
    s_log.info("END new object.");
    s_log.info("");
    s_log.info("");
  }
 private void remoteGetBeforeWrite(
     InvocationContext ctx, boolean isConditionalCommand, KeyGenerator keygen) throws Throwable {
   // this should only happen if:
   //   a) unsafeUnreliableReturnValues is false
   //   b) unsafeUnreliableReturnValues is true, we are in a TX and the command is conditional
   if (isNeedReliableReturnValues(ctx) || (isConditionalCommand && ctx.isInTxScope())) {
     for (Object k : keygen.getKeys()) remoteGetAndStoreInL1(ctx, k, true);
   }
 }
Esempio n. 18
0
 public static String getStringKey() throws EncryptionException {
   SecretKey key = null;
   try {
     key = KeyGenerator.getInstance(ALGO).generateKey();
   } catch (NoSuchAlgorithmException e) {
     throw new EncryptionException("Cannot generate a secret key" + '\n' + e.getMessage());
   }
   return Base64.encodeBase64String(key.getEncoded());
 }
Esempio n. 19
0
 public static SecretKey getSecretKey() throws EncryptionException {
   SecretKey key = null;
   try {
     key = KeyGenerator.getInstance(ALGO).generateKey();
   } catch (NoSuchAlgorithmException e) {
     throw new EncryptionException("Cannot generate a secret key" + '\n' + e.getMessage());
   }
   return key;
 }
Esempio n. 20
0
  public String putFragment(String fragment) {
    int fragmentVal = validateAndConvertFragment(fragment);

    for (Segment segment : this.segments) {
      if (segment.valueWithinLimits(fragmentVal)) {
        if (!segment.hasMetadataKey(Segment.SIGNIFICANT_BITS_IN_LAST_FRAGMENT_KEY)) {
          String sigBitsKey = keyGenerator.next();
          // Log.d(TAG, "Setting sig-bit metadata key for \"" + segment.getAction() + "\" to \"" +
          // sigBitsKey + "\"");
          segment.setMetadataKey(Segment.SIGNIFICANT_BITS_IN_LAST_FRAGMENT_KEY, sigBitsKey);

          String segmentNumberKey = keyGenerator.next();
          // Log.d(TAG, "Setting segment number metadata key for \"" + segment.getAction() + "\" to
          // \"" + segmentNumberKey + "\"");
          segment.setMetadataKey(Segment.SEGMENT_NUMBER_KEY, segmentNumberKey);

          String segmentCountKey = keyGenerator.next();
          // Log.d(TAG, "Setting segment count metadata key for \"" + segment.getAction() + "\" to
          // \"" + segmentCountKey + "\"");
          segment.setMetadataKey(Segment.MESSAGE_SEGMENT_COUNT_KEY, segmentCountKey);
        }

        String key = keyGenerator.next();

        // TODO: Remove the duplication between these
        segment.addFragment(key, fragment);
        fragmentKeyMap.put(key, fragment);

        // Update the number of significant bits in the last fragment (i.e. the one that was just
        // added)
        int sigBitsInFragment = fragment.length();

        // Log.d(TAG, "Setting significant bits for \"" + segment.getAction() + "\" to " +
        // sigBitsInFragment);

        String sigBitsMetadataFragmentBitstring = Integer.toBinaryString(sigBitsInFragment);
        segment.setMetadataValue(
            Segment.SIGNIFICANT_BITS_IN_LAST_FRAGMENT_KEY, sigBitsMetadataFragmentBitstring);
        return key;
      }
    }

    return null; // This should never happen
  }
Esempio n. 21
0
 @SuppressWarnings("restriction")
 public String getencrypt(String p) throws Exception {
   String encrypted = "";
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(KEY.getBytes()));
     SecretKey skey = kgen.generateKey();
     byte[] raw = skey.getEncoded();
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
     byte[] encrypt = cipher.doFinal(p.getBytes());
     encrypted = new BASE64Encoder().encodeBuffer(encrypt).trim();
     // System.out.println("encrypted="+encrypted);
   } // try
   catch (Exception e) {
     System.out.println(e);
   }
   return encrypted; // return 密文
 }
Esempio n. 22
0
  /** Creates a new instance of Encrypter */
  public AltEncrypter(String passPhrase) {

    try {
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(passPhrase.getBytes("UTF8"));
      KeyGenerator kGen = KeyGenerator.getInstance("DESEDE");
      kGen.init(168, sr);
      Key key = kGen.generateKey();

      cipherEncrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);

      cipherDecrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
    } catch (UnsupportedEncodingException e) {
    } catch (NoSuchPaddingException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidKeyException e) {
    }
  }
Esempio n. 23
0
  public String getdecrypt(String base64) throws Exception {
    String decrypted = "";
    try {
      @SuppressWarnings("restriction")
      byte[] b = new BASE64Decoder().decodeBuffer(base64);
      KeyGenerator kgen2 = KeyGenerator.getInstance("AES");
      kgen2.init(128, new SecureRandom(KEY.getBytes()));
      SecretKey skey2 = kgen2.generateKey();
      byte[] raw2 = skey2.getEncoded();
      SecretKeySpec skeySpec2 = new SecretKeySpec(raw2, "AES");
      Cipher cipher2 = Cipher.getInstance("AES");
      cipher2.init(Cipher.DECRYPT_MODE, skeySpec2);
      byte[] decrypt = cipher2.doFinal(b);
      decrypted = new String(decrypt);
      // System.out.println("decrypted="+decrypted);

    } catch (Exception e) {
      System.out.println(e);
    }
    return decrypted;
  }
 /** {@inheritDoc} */
 protected void initCipher(final char[] password) {
   final byte[] derivedKey = generator.generate(password, DKEY_BIT_LENGTH);
   final byte[] keyBytes = new byte[KEY_LENGTH];
   System.arraycopy(derivedKey, 0, keyBytes, 0, KEY_LENGTH);
   cipher.setKey(new SecretKeySpec(keyBytes, cipher.getAlgorithm()));
   if (!cipher.hasIV()) {
     // Use the generated IV value
     final byte[] ivBytes = new byte[IV_LENGTH];
     System.arraycopy(derivedKey, KEY_LENGTH, ivBytes, 0, IV_LENGTH);
     cipher.setIV(ivBytes);
   }
 }
Esempio n. 25
0
  public Encrypter() {
    try {
      SecretKey key = KeyGenerator.getInstance("DES").generateKey();
      ecipher = Cipher.getInstance("DES");
      dcipher = Cipher.getInstance("DES");
      ecipher.init(Cipher.ENCRYPT_MODE, key);
      dcipher.init(Cipher.DECRYPT_MODE, key);

    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
  }
Esempio n. 26
0
  /** Generates server's keys for signature */
  public void generateKeys() {
    Logging.getLogger().info("Generating keypair");

    try {
      String[] pair = KeyGenerator.generateKeyPair();
      myConnectInfo =
          new ConnectInfo("server", this.serverIp, this.serverIp, this.port, pair[1], "Server");
      this.connections.add(myConnectInfo);
      this.signer = new Signer(pair[0]);
    } catch (SignatureException e) {
      Logging.getLogger().severe("Unable to generate keypair : " + e);
      System.exit(1);
    }
  }
Esempio n. 27
0
  /** performs any cleanup before exiting the program */
  @Override
  protected void cleanUp() throws java.lang.Exception {
    // remove the listeners at the buttons
    RevokeButtons aRevoke = new RevokeButtons(m_aOperator);
    aRevoke.handle(m_document.getFormComponentTreeRoot());

    // remove the key generator listeners from the form
    m_aSalesmanKeyGenerator.stopGenerator();
    m_aSalesKeyGenerator.stopGenerator();

    // and the control lockers
    m_aSalesmenLocker.enableLock(false);
    m_aSalesLocker.enableLock(false);

    // the validator for the grid column
    m_aSalesNameValidator.enableColumnWatch(false);

    // remove our own reset listener from the form
    XNameAccess xMasterAsNames = UnoRuntime.queryInterface(XNameAccess.class, m_xMasterForm);
    XReset xFormReset = UNO.queryReset(xMasterAsNames.getByName("Sales"));
    xFormReset.removeResetListener(this);

    super.cleanUp();
  }
Esempio n. 28
0
  public static void main(String[] args) {
    try {
      if (args[0].equals("-genkey")) {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(KEYSIZE, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
        out.writeObject(keyPair.getPublic());
        out.close();
        out = new ObjectOutputStream(new FileOutputStream(args[2]));
        out.writeObject(keyPair.getPrivate());
        out.close();
      } else if (args[0].equals("-encrypt")) {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        SecretKey key = keygen.generateKey();

        // wrap with RSA public key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key publicKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
        out.writeInt(wrappedKey.length);
        out.write(wrappedKey);

        InputStream in = new FileInputStream(args[1]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      } else {
        DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
        int length = in.readInt();
        byte[] wrappedKey = new byte[length];
        in.read(wrappedKey, 0, length);

        // unwrap with RSA private key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key privateKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

        OutputStream out = new FileOutputStream(args[2]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        crypt(in, out, cipher);
        in.close();
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Esempio n. 29
-1
  /*
   * Calculate the keys needed for this connection, once the session's
   * master secret has been calculated.  Uses the master key and nonces;
   * the amount of keying material generated is a function of the cipher
   * suite that's been negotiated.
   *
   * This gets called both on the "full handshake" (where we exchanged
   * a premaster secret and started a new session) as well as on the
   * "fast handshake" (where we just resumed a pre-existing session).
   */
  void calculateConnectionKeys(SecretKey masterKey) {
    /*
     * For both the read and write sides of the protocol, we use the
     * master to generate MAC secrets and cipher keying material.  Block
     * ciphers need initialization vectors, which we also generate.
     *
     * First we figure out how much keying material is needed.
     */
    int hashSize = cipherSuite.macAlg.size;
    boolean is_exportable = cipherSuite.exportable;
    BulkCipher cipher = cipherSuite.cipher;
    int expandedKeySize = is_exportable ? cipher.expandedKeySize : 0;

    // Which algs/params do we need to use?
    String keyMaterialAlg;
    PRF prf;

    if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
      keyMaterialAlg = "SunTls12KeyMaterial";
      prf = cipherSuite.prfAlg;
    } else {
      keyMaterialAlg = "SunTlsKeyMaterial";
      prf = P_NONE;
    }

    String prfHashAlg = prf.getPRFHashAlg();
    int prfHashLength = prf.getPRFHashLength();
    int prfBlockSize = prf.getPRFBlockSize();

    TlsKeyMaterialParameterSpec spec =
        new TlsKeyMaterialParameterSpec(
            masterKey,
            protocolVersion.major,
            protocolVersion.minor,
            clnt_random.random_bytes,
            svr_random.random_bytes,
            cipher.algorithm,
            cipher.keySize,
            expandedKeySize,
            cipher.ivSize,
            hashSize,
            prfHashAlg,
            prfHashLength,
            prfBlockSize);

    try {
      KeyGenerator kg = JsseJce.getKeyGenerator(keyMaterialAlg);
      kg.init(spec);
      TlsKeyMaterialSpec keySpec = (TlsKeyMaterialSpec) kg.generateKey();

      clntWriteKey = keySpec.getClientCipherKey();
      svrWriteKey = keySpec.getServerCipherKey();

      // Return null if IVs are not supposed to be generated.
      // e.g. TLS 1.1+.
      clntWriteIV = keySpec.getClientIv();
      svrWriteIV = keySpec.getServerIv();

      clntMacSecret = keySpec.getClientMacKey();
      svrMacSecret = keySpec.getServerMacKey();
    } catch (GeneralSecurityException e) {
      throw new ProviderException(e);
    }

    //
    // Dump the connection keys as they're generated.
    //
    if (debug != null && Debug.isOn("keygen")) {
      synchronized (System.out) {
        HexDumpEncoder dump = new HexDumpEncoder();

        System.out.println("CONNECTION KEYGEN:");

        // Inputs:
        System.out.println("Client Nonce:");
        printHex(dump, clnt_random.random_bytes);
        System.out.println("Server Nonce:");
        printHex(dump, svr_random.random_bytes);
        System.out.println("Master Secret:");
        printHex(dump, masterKey.getEncoded());

        // Outputs:
        System.out.println("Client MAC write Secret:");
        printHex(dump, clntMacSecret.getEncoded());
        System.out.println("Server MAC write Secret:");
        printHex(dump, svrMacSecret.getEncoded());

        if (clntWriteKey != null) {
          System.out.println("Client write key:");
          printHex(dump, clntWriteKey.getEncoded());
          System.out.println("Server write key:");
          printHex(dump, svrWriteKey.getEncoded());
        } else {
          System.out.println("... no encryption keys used");
        }

        if (clntWriteIV != null) {
          System.out.println("Client write IV:");
          printHex(dump, clntWriteIV.getIV());
          System.out.println("Server write IV:");
          printHex(dump, svrWriteIV.getIV());
        } else {
          if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
            System.out.println("... no IV derived for this protocol");
          } else {
            System.out.println("... no IV used for this cipher");
          }
        }
        System.out.flush();
      }
    }
  }
Esempio n. 30
-5
  /*
   * Calculate the master secret from its various components.  This is
   * used for key exchange by all cipher suites.
   *
   * The master secret is the catenation of three MD5 hashes, each
   * consisting of the pre-master secret and a SHA1 hash.  Those three
   * SHA1 hashes are of (different) constant strings, the pre-master
   * secret, and the nonces provided by the client and the server.
   */
  private SecretKey calculateMasterSecret(
      SecretKey preMasterSecret, ProtocolVersion requestedVersion) {

    if (debug != null && Debug.isOn("keygen")) {
      HexDumpEncoder dump = new HexDumpEncoder();

      System.out.println("SESSION KEYGEN:");

      System.out.println("PreMaster Secret:");
      printHex(dump, preMasterSecret.getEncoded());

      // Nonces are dumped with connection keygen, no
      // benefit to doing it twice
    }

    // What algs/params do we need to use?
    String masterAlg;
    PRF prf;

    if (protocolVersion.v >= ProtocolVersion.TLS12.v) {
      masterAlg = "SunTls12MasterSecret";
      prf = cipherSuite.prfAlg;
    } else {
      masterAlg = "SunTlsMasterSecret";
      prf = P_NONE;
    }

    String prfHashAlg = prf.getPRFHashAlg();
    int prfHashLength = prf.getPRFHashLength();
    int prfBlockSize = prf.getPRFBlockSize();

    TlsMasterSecretParameterSpec spec =
        new TlsMasterSecretParameterSpec(
            preMasterSecret,
            protocolVersion.major,
            protocolVersion.minor,
            clnt_random.random_bytes,
            svr_random.random_bytes,
            prfHashAlg,
            prfHashLength,
            prfBlockSize);

    SecretKey masterSecret;
    try {
      KeyGenerator kg = JsseJce.getKeyGenerator(masterAlg);
      kg.init(spec);
      masterSecret = kg.generateKey();
    } catch (GeneralSecurityException e) {
      // For RSA premaster secrets, do not signal a protocol error
      // due to the Bleichenbacher attack. See comments further down.
      if (!preMasterSecret.getAlgorithm().equals("TlsRsaPremasterSecret")) {
        throw new ProviderException(e);
      }

      if (debug != null && Debug.isOn("handshake")) {
        System.out.println("RSA master secret generation error:");
        e.printStackTrace(System.out);
        System.out.println("Generating new random premaster secret");
      }

      if (requestedVersion != null) {
        preMasterSecret = RSAClientKeyExchange.generateDummySecret(requestedVersion);
      } else {
        preMasterSecret = RSAClientKeyExchange.generateDummySecret(protocolVersion);
      }

      // recursive call with new premaster secret
      return calculateMasterSecret(preMasterSecret, null);
    }

    // if no version check requested (client side handshake), or version
    // information is not available (not an RSA premaster secret),
    // return master secret immediately.
    if ((requestedVersion == null) || !(masterSecret instanceof TlsMasterSecret)) {
      return masterSecret;
    }

    // we have checked the ClientKeyExchange message when reading TLS
    // record, the following check is necessary to ensure that
    // JCE provider does not ignore the checking, or the previous
    // checking process bypassed the premaster secret version checking.
    TlsMasterSecret tlsKey = (TlsMasterSecret) masterSecret;
    int major = tlsKey.getMajorVersion();
    int minor = tlsKey.getMinorVersion();
    if ((major < 0) || (minor < 0)) {
      return masterSecret;
    }

    // check if the premaster secret version is ok
    // the specification says that it must be the maximum version supported
    // by the client from its ClientHello message. However, many
    // implementations send the negotiated version, so accept both
    // for SSL v3.0 and TLS v1.0.
    // NOTE that we may be comparing two unsupported version numbers, which
    // is why we cannot use object reference equality in this special case.
    ProtocolVersion premasterVersion = ProtocolVersion.valueOf(major, minor);
    boolean versionMismatch = (premasterVersion.v != requestedVersion.v);

    /*
     * we never checked the client_version in server side
     * for TLS v1.0 and SSL v3.0. For compatibility, we
     * maintain this behavior.
     */
    if (versionMismatch && requestedVersion.v <= ProtocolVersion.TLS10.v) {
      versionMismatch = (premasterVersion.v != protocolVersion.v);
    }

    if (versionMismatch == false) {
      // check passed, return key
      return masterSecret;
    }

    // Due to the Bleichenbacher attack, do not signal a protocol error.
    // Generate a random premaster secret and continue with the handshake,
    // which will fail when verifying the finished messages.
    // For more information, see comments in PreMasterSecret.
    if (debug != null && Debug.isOn("handshake")) {
      System.out.println(
          "RSA PreMasterSecret version error: expected"
              + protocolVersion
              + " or "
              + requestedVersion
              + ", decrypted: "
              + premasterVersion);
      System.out.println("Generating new random premaster secret");
    }
    preMasterSecret = RSAClientKeyExchange.generateDummySecret(requestedVersion);

    // recursive call with new premaster secret
    return calculateMasterSecret(preMasterSecret, null);
  }