예제 #1
0
 public RSAJweEncryption(RSAPublicKey publicKey, SecretKey secretKey, byte[] iv) {
   this(
       publicKey,
       secretKey,
       Algorithm.toJwtName(secretKey.getAlgorithm(), secretKey.getEncoded().length * 8),
       iv);
 }
예제 #2
0
파일: MAC.java 프로젝트: MondayIsSun/J2SE
  public static void jdkHMacMD5() {
    KeyGenerator keyGenerator;
    try {
      // 生成密钥
      // keyGenerator = KeyGenerator.getInstance("HmacMD5");
      // SecretKey secretKey = keyGenerator.generateKey();
      // byte[] key = secretKey.getEncoded();
      byte[] key = Hex.decodeHex(new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'});

      // 还原密钥
      SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");

      // 实例和初始化Mac
      Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
      mac.init(restoreSecretKey);

      // 执行摘要
      byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());
      System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes));

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (DecoderException e) {
      e.printStackTrace();
    }
  }
예제 #3
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;
  }
예제 #4
0
  /**
   * This method broadcasts a payload onto the given topic.
   *
   * @param topic the topic to broadcast onto
   * @param visibility the visibility of the message
   * @param payload the payload of the message
   */
  public void broadcast(String topic, Visibility visibility, byte[] payload) throws IOException {
    byte[] payloadToSend = payload;
    SecureMessage message = new SecureMessage();
    message.setVisibility(visibility);
    if (isProduction) {
      try {
        // Generate a new symmetric key and encrypt the message
        Cipher cipher = Cipher.getInstance(ALGO);
        KeyGenerator gen = KeyGenerator.getInstance(ALGO);
        gen.init(256);
        SecretKey key = gen.generateKey();
        cipher.init(Cipher.ENCRYPT_MODE, key);
        payloadToSend = cipher.doFinal(payload);

        // Get topic crypto object, encrypt the key and embed it into the message
        RSAKeyCrypto crypto = topicKeys.get(topic);
        message.setKey(crypto.encrypt(key.getEncoded()));
      } catch (Exception e) {
        log.error("Could not encrypt message for topic [{}].", topic, e);
        throw new RuntimeException(e);
      }
    }
    message.setContent(payloadToSend);
    byte[] serializedMessage;
    try {
      serializedMessage = ThriftUtils.serialize(message);
    } catch (TException e) {
      throw new IOException("Could not serialize message", e);
    }
    broadcastImpl(topic, serializedMessage);
  }
  private String generateRandomMACHash(int algorithm) throws Exception {
    // Generates a secret key
    SecretKey sk = null;
    switch (algorithm) {
      case RandomValueMeta.TYPE_RANDOM_MAC_HMACMD5:
        sk = data.keyGenHmacMD5.generateKey();
        break;
      case RandomValueMeta.TYPE_RANDOM_MAC_HMACSHA1:
        sk = data.keyGenHmacSHA1.generateKey();
        break;
      default:
        break;
    }

    if (sk == null) {
      throw new KettleException(BaseMessages.getString(PKG, "RandomValue.Log.SecretKeyNull"));
    }

    // Create a MAC object using HMAC and initialize with key
    Mac mac = Mac.getInstance(sk.getAlgorithm());
    mac.init(sk);
    // digest
    byte[] hashCode = mac.doFinal();
    StringBuilder encoded = new StringBuilder();
    for (int i = 0; i < hashCode.length; i++) {
      String _b = Integer.toHexString(hashCode[i]);
      if (_b.length() == 1) {
        _b = "0" + _b;
      }
      encoded.append(_b.substring(_b.length() - 2));
    }

    return encoded.toString();
  }
예제 #6
0
  /**
   * @param p
   * @throws java.security.InvalidKeyException
   * @throws java.io.UnsupportedEncodingException
   * @throws java.security.spec.InvalidKeySpecException
   * @throws java.security.NoSuchAlgorithmException
   * @throws javax.crypto.NoSuchPaddingException
   */
  public void setPassword(String p) throws FacesException {
    byte[] s = {
      (byte) 0xA9,
      (byte) 0x9B,
      (byte) 0xC8,
      (byte) 0x32,
      (byte) 0x56,
      (byte) 0x34,
      (byte) 0xE3,
      (byte) 0x03
    };

    try {
      KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
      SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);

      e = Cipher.getInstance(key.getAlgorithm());
      d = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameters to the cipthers
      //          AlgorithmParameterSpec paramSpec = new IvParameterSpec(s);
      e.init(Cipher.ENCRYPT_MODE, key);
      d.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
      throw new FacesException("Error set encryption key", e);
    }
  }
예제 #7
0
  public static String decode(String token) {
    if (token == null) {
      return null;
    }
    try {

      String input =
          token.replace("%0A", "\n").replace("%25", "%").replace('_', '/').replace('-', '+');

      byte[] dec = Base64.decodeBase64(input.getBytes());

      KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);

      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

      Cipher dcipher = Cipher.getInstance(key.getAlgorithm());
      dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

      byte[] decoded = dcipher.doFinal(dec);

      String result = new String(decoded);
      return result;

    } catch (Exception e) {
      // use logger in production code
      e.printStackTrace();
    }

    return null;
  }
  private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
      throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator =
        AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream =
        new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo =
        computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier =
        new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo =
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
  }
예제 #9
0
    protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec)
        throws InvalidKeySpecException {
      if (keySpec == null) {
        throw new InvalidKeySpecException("keySpec parameter is null");
      }
      if (key == null) {
        throw new InvalidKeySpecException("key parameter is null");
      }

      if (SecretKeySpec.class.isAssignableFrom(keySpec)) {
        return new SecretKeySpec(key.getEncoded(), algName);
      } else if (DESedeKeySpec.class.isAssignableFrom(keySpec)) {
        byte[] bytes = key.getEncoded();

        try {
          if (bytes.length == 16) {
            byte[] longKey = new byte[24];

            System.arraycopy(bytes, 0, longKey, 0, 16);
            System.arraycopy(bytes, 0, longKey, 16, 8);

            return new DESedeKeySpec(longKey);
          } else {
            return new DESedeKeySpec(bytes);
          }
        } catch (Exception e) {
          throw new InvalidKeySpecException(e.toString());
        }
      }

      throw new InvalidKeySpecException("Invalid KeySpec");
    }
  protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec) throws InvalidKeySpecException {
    if (keySpec == null) {
      throw new InvalidKeySpecException("keySpec parameter is null");
    }
    if (key == null) {
      throw new InvalidKeySpecException("key parameter is null");
    }

    if (SecretKeySpec.class.isAssignableFrom(keySpec)) {
      return new SecretKeySpec(key.getEncoded(), algName);
    }

    try {
      Class[] parameters = {byte[].class};

      Constructor c = keySpec.getConstructor(parameters);
      Object[] p = new Object[1];

      p[0] = key.getEncoded();

      return (KeySpec) c.newInstance(p);
    } catch (Exception e) {
      throw new InvalidKeySpecException(e.toString());
    }
  }
예제 #11
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bm = null;
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen;
    try {
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(keyStart);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();

      // encrypt
      byte[] encryptedData = encrypt(key, b);
      // decrypt
      byte[] decryptedData = decrypt(key, encryptedData);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    } catch (Exception e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    }
  }
예제 #12
0
  /**
   * Defautl constructor for creating a DES encrypt/decryption mechanism.
   *
   * @param passPhrase
   */
  private claves(String passPhrase) {
    try {
      // Create the key
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT, iterationCount);
      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

      enryptCipher = Cipher.getInstance(key.getAlgorithm());
      decriptCipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, iterationCount);

      // Create the ciphers
      enryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
      decriptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

    } catch (java.security.InvalidAlgorithmParameterException e) {
      encrypter = null;
    } catch (java.security.spec.InvalidKeySpecException e) {
      encrypter = null;
    } catch (javax.crypto.NoSuchPaddingException e) {
      encrypter = null;
    } catch (java.security.NoSuchAlgorithmException e) {
      encrypter = null;
    } catch (java.security.InvalidKeyException e) {
      encrypter = null;
    }
  }
예제 #13
0
파일: AES.java 프로젝트: zengboming/JAVA
  protected String decrypt(String content, String key) {

    if (content.length() < 1) return null;
    byte[] byteRresult = new byte[content.length() / 2];
    for (int i = 0; i < content.length() / 2; i++) {
      int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
      int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
      byteRresult[i] = (byte) (high * 16 + low);
    }
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128, new SecureRandom(key.getBytes()));
      SecretKey secretKey = kgen.generateKey();
      byte[] enCodeFormat = secretKey.getEncoded();
      SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
      byte[] result = cipher.doFinal(byteRresult);
      return new String(result);
    } 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;
  }
예제 #14
0
파일: AES.java 프로젝트: zengboming/JAVA
 protected String encrypt(String content, String key) {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(key.getBytes()));
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
     byte[] byteRresult = cipher.doFinal(byteContent);
     StringBuffer sb = new StringBuffer();
     for (int i = 0; i < byteRresult.length; i++) {
       String hex = Integer.toHexString(byteRresult[i] & 0xFF);
       if (hex.length() == 1) {
         hex = '0' + hex;
       }
       sb.append(hex.toUpperCase());
     }
     return sb.toString();
   } 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;
 }
예제 #15
0
  public static String encode(String input) {
    if (input == null) {
      throw new IllegalArgumentException();
    }
    try {

      KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT);
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT);

      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

      Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
      ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

      byte[] enc = ecipher.doFinal(input.getBytes());

      String res = new String(Base64.encodeBase64(enc));
      // escapes for url
      res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A");

      return res;

    } catch (Exception e) {
    }

    return "";
  }
예제 #16
0
  public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException {
    Message message = new Message();
    message.pubKey = pubKey.getEncoded();

    KeyGenerator keyGen;
    try {
      keyGen = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(e);
    }
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();

    try {
      Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
      message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded());

      Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
      AlgorithmParameters params = aesCipher.getParameters();
      message.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
      message.ciphertext = aesCipher.doFinal(input);
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException
        | BadPaddingException
        | InvalidParameterSpecException e) {
      throw new CryptoException(e);
    }

    return message;
  }
예제 #17
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;
 }
예제 #18
0
  /**
   * Get the signing key unique to this installation, or create it if it doesn't exist. The purpose
   * of this key is to allow signing of backup files (and any other such files) to ensure they are
   * not modified by some other program. Of course, if the other program has root then it can modify
   * or read this key anyway, so all bets are off.
   *
   * @return secret key for signing and verification
   */
  public SecretKey getOrCreateSigningKey() {
    String signingKey = this.prefs.getString(BACKUP_SIGNING_KEY, null);
    SecretKey secretKey = null;
    if (signingKey != null) {
      secretKey =
          new SecretKeySpec(
              Base64.decode(signingKey, Base64.DEFAULT),
              0,
              Base64.decode(signingKey, Base64.DEFAULT).length,
              "HmacSHA1");
    } else {
      // supporting multiple algorithms would be good, but then we also need to store the key
      // type...
      try {
        secretKey = KeyGenerator.getInstance("HmacSHA1").generateKey();
      } catch (NoSuchAlgorithmException e) {
      }

      Editor editor = this.prefs.edit();
      editor.putString(
          BACKUP_SIGNING_KEY, Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT));
      editor.commit();
    }

    return secretKey;
  }
예제 #19
0
  private void testCipherNameWithWrap(String name, String simpleName) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();

    byte[] salt = {
      (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
      (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
    };
    char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC");

    pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec);

    byte[] symKeyBytes = pbeEncryptCipher.wrap(key);

    Cipher simpleCipher = Cipher.getInstance(simpleName, "SC");

    simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec);

    SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY);

    if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) {
      fail("key mismatch on unwrapping");
    }
  }
예제 #20
0
  EncryptStrings(String passPhrase) {
    try {
      // Create the key
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
      SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
      ecipher = Cipher.getInstance(key.getAlgorithm());
      dcipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

      // Create the ciphers
      ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
      dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

      System.out.println(ecipher.doFinal());

    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    } catch (IllegalBlockSizeException ex) {
      Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
      Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #21
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);
     }
   }
 }
예제 #22
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + confidentialityKey.hashCode();
   result = prime * result + integrityKey.hashCode();
   return result;
 }
예제 #23
0
  private static Cipher getCipherFromPassphrase(
      String passphrase, byte[] salt, int iterations, int opMode) throws GeneralSecurityException {
    SecretKey key = getKeyFromPassphrase(passphrase, salt, iterations);
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(opMode, key, new PBEParameterSpec(salt, iterations));

    return cipher;
  }
예제 #24
0
파일: PIN.java 프로젝트: rufuszhu/Test
 // using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
 // cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
 private static String hash(String password, byte[] salt) throws Exception {
   if (password == null || password.length() == 0)
     throw new IllegalArgumentException("Empty passwords are not supported.");
   SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
   SecretKey key =
       f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
   return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
 }
예제 #25
0
파일: DES.java 프로젝트: chinahuangxin/prjs
 public static void setKeyCode() {
   try {
     KeyGenerator keygen = KeyGenerator.getInstance("DES");
     SecretKey deskey = keygen.generateKey();
     keyCode = baseEncode(deskey.getEncoded());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 private static byte[] getRawKey(byte[] seed) throws Exception {
   KeyGenerator kgen = KeyGenerator.getInstance("AES");
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(seed);
   kgen.init(128, sr); // 192 and 256 bits may not be available
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
예제 #27
0
 private byte[] getRawKey(byte[] seed) throws Exception {
   KeyGenerator kgen = KeyGenerator.getInstance("AES");
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
   sr.setSeed(seed);
   kgen.init(128, sr);
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
예제 #28
0
 private byte[] getRawKey(byte[] seed) throws NoSuchAlgorithmException {
   KeyGenerator kgen = KeyGenerator.getInstance(PASS_ALGO);
   SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(seed);
   kgen.init(128, sr);
   SecretKey skey = kgen.generateKey();
   byte[] raw = skey.getEncoded();
   return raw;
 }
예제 #29
0
  public static void main(String[] args) throws Exception {
    // Gen Key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
    SecretKey key = keyGenerator.generateKey();
    bytesKey = key.getEncoded();

    jdkDES();
    bcDES();
  }
예제 #30
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());
 }