Example #1
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();
    }
  }
 /**
  * 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);
     }
   }
 }
Example #3
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;
 }
Example #4
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;
  }
 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"));
 }
Example #6
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;
 }
Example #7
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());
 }
  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);

  }
  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) {

    }
  }
Example #10
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);
   }
 }
Example #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;
  }
Example #13
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) {
    }
  }
Example #14
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) {
    }
  }
Example #15
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 密文
 }
Example #16
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;
  }
Example #17
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();
    }
  }
Example #18
0
 /**
  * Constructs a new QuickChipher with the given transformation and algorithm.
  *
  * @param transformation the transformation to be used to create the Cipher for this QuickCipher.
  * @param algorithm the algorithm to be used to create the SecretKey for this QuickCipher.
  * @throws NoSuchAlgorithmException if transformation is null, empty, in an invalid format, or if
  *     no Provider supports a CipherSpi implementation for the specified algorithm or if no
  *     Provider supports a KeyGeneratorSpi implementation for the specified algorithm.
  * @throws NoSuchPaddingException if transformation contains a padding scheme that is not
  *     available.
  */
 public QuickCipher(String transformation, String algorithm)
     throws NoSuchAlgorithmException, NoSuchPaddingException {
   this.algorithm = algorithm;
   cipher = Cipher.getInstance(transformation);
   key = KeyGenerator.getInstance(this.algorithm).generateKey();
 }