Java Code Examples for javax.crypto.spec.SecretKeySpec#getEncoded()

The following examples show how to use javax.crypto.spec.SecretKeySpec#getEncoded() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AES.java    From aes-rsa-java with Apache License 2.0 6 votes vote down vote up
/**
 * 加密
 *
 * @param data 需要加密的内容
 * @param key  加密密码
 * @return
 */
public static byte[] encrypt(byte[] data, byte[] key) {
    CheckUtils.notEmpty(data, "data");
    CheckUtils.notEmpty(key, "key");
    if (key.length != 16) {
        throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
    }
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.AES_ALGORITHM);// 创建密码器
        IvParameterSpec iv = new IvParameterSpec(key);//使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, seckey, iv);// 初始化
        byte[] result = cipher.doFinal(data);
        return result; // 加密
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("encrypt fail!", e);
    }
}
 
Example 2
Source File: AES.java    From aes-rsa-java with Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 *
 * @param data 待解密内容
 * @param key  解密密钥
 * @return
 */
public static byte[] decrypt(byte[] data, byte[] key) {
    CheckUtils.notEmpty(data, "data");
    CheckUtils.notEmpty(key, "key");
    if (key.length != 16) {
        throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
    }
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.AES_ALGORITHM);// 创建密码器
        IvParameterSpec iv = new IvParameterSpec(key);//使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.DECRYPT_MODE, seckey, iv);// 初始化
        byte[] result = cipher.doFinal(data);
        return result; // 解密
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("decrypt fail!", e);
    }
}
 
Example 3
Source File: SecretKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * getEncoded() method testing. Tests that returned array is equal to the
 * array specified in the constructor. Checks that modification
 * of returned array does not affect the internal array.
 */
public void testGetEncoded() {
    byte[] key = new byte[] {1, 2, 3, 4, 5};
    String algorithm = "Algorithm";

    SecretKeySpec ks = new SecretKeySpec(key, algorithm);
    byte[] result = ks.getEncoded();
    if (! Arrays.equals(key, result)) {
        fail("The returned key does not equal to the specified "
                + "in the constructor.");
    }
    result[0] ++;
    assertFalse("The change of returned by getEncoded() method key "
                + "should not cause the change of internal array.",
                result[0] == ks.getEncoded()[0]);

    // Regression for HARMONY-78
    int offset = 1;
    int len = 4;
    SecretKeySpec sks = new SecretKeySpec(key, offset, len, algorithm);
    assertEquals("Key length is incorrect", len, sks.getEncoded().length);
}
 
Example 4
Source File: DecryptTools.java    From wechattool with MIT License 5 votes vote down vote up
public static final String decrypt(String filename,byte xor) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidAlgorithmParameterException {

        FileInputStream fileInputStream = new FileInputStream(new File(filename));
        byte[] bytes = fileInputStream.readAllBytes();

        byte[] inb =new byte[0x400];
        for(int i=0;i<inb.length;i++){
            inb[i]= bytes[i];
        }
        Security.addProvider(new BouncyCastleProvider());

        byte[] keyBytes = get("3a1f12ef91839f1e3745d4368dae3de2");
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        byte[] encoded = keySpec.getEncoded();

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding","BC");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(encoded));
        byte[] result = cipher.doFinal(inb);
        for(int i=0;i<result.length;i++){
            result[i]= (byte) (result[i] ^ xor);
        }
        String plainText = new String(result);
        System.out.println(xor+"==========");
        System.out.println(plainText.substring(0x300,0xff));

        FileOutputStream outputStream=new FileOutputStream(new File("./"+xor+"abc"));
        outputStream.write(result);
        for(int i=0x400;i<bytes.length;i++){
            outputStream.write(bytes[i]);
        }
        outputStream.close();
        return plainText;
    }
 
Example 5
Source File: EncodingBenchmark.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public SimpleCredentialStore() {
  SecureRandom r = new SecureRandom();
  byte[] keyBytes = new byte[16];
  r.nextBytes(keyBytes);

  key = new SecretKeySpec(keyBytes, "AES");
  keyEncoded = key.getEncoded();
}
 
Example 6
Source File: GCMCryptoService.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer encryptKey(SecretKeySpec toEncrypt, SecretKeySpec key) throws GeneralSecurityException {
  byte[] encodedKey = toEncrypt.getEncoded();
  ByteBuffer keyRecordBuffer =
      ByteBuffer.allocate(KeyRecord_Format_V1.getKeyRecordSize(encodedKey, toEncrypt.getAlgorithm()));
  KeyRecord_Format_V1.serializeKeyRecord(keyRecordBuffer, encodedKey, toEncrypt.getAlgorithm());
  keyRecordBuffer.flip();
  return encrypt(keyRecordBuffer, key);
}
 
Example 7
Source File: UDPConnectionSet.java    From BiglyBT with GNU General Public License v2.0 4 votes vote down vote up
private RC4Engine
getCipher(
	byte[]			key )
{
    SecretKeySpec	secret_key_spec = new SecretKeySpec( key, "RC4" );

    RC4Engine rc4_engine	= new RC4Engine();

	CipherParameters	params_a = new KeyParameter( secret_key_spec.getEncoded());

		// for RC4 enc/dec is irrelevant

	rc4_engine.init( true, params_a );

		// skip first 1024 bytes of stream to protected against a Fluhrer, Mantin and Shamir attack

   	byte[]	temp = new byte[1024];

   	rc4_engine.processBytes( temp, 0, temp.length, temp, 0 );

   	return( rc4_engine );
}
 
Example 8
Source File: UDPConnectionSet.java    From TorrentEngine with GNU General Public License v3.0 4 votes vote down vote up
private RC4Engine
getCipher(
	byte[]			key )
{
    SecretKeySpec	secret_key_spec = new SecretKeySpec( key, "RC4" );

    RC4Engine rc4_engine	= new RC4Engine();

	CipherParameters	params_a = new KeyParameter( secret_key_spec.getEncoded());

		// for RC4 enc/dec is irrelevant

	rc4_engine.init( true, params_a );

		// skip first 1024 bytes of stream to protected against a Fluhrer, Mantin and Shamir attack

   	byte[]	temp = new byte[1024];

   	rc4_engine.processBytes( temp, 0, temp.length, temp, 0 );

   	return( rc4_engine );
}
 
Example 9
Source File: TransportCipher.java    From BiglyBT with GNU General Public License v2.0 2 votes vote down vote up
TransportCipher(
	String					algorithm,
	int						mode,
	SecretKeySpec			key_spec )

	throws Exception
{
    if ( algorithm.equals( "RC4" )){

    	if ( !internal_rc4 ){

    		try{
    	    	cipher = Cipher.getInstance( algorithm );

    	    	cipher.init( mode, key_spec );

    		}catch( Throwable e ){

    			internal_rc4	= true;
    		}
    	}

    	if ( internal_rc4 ){

    		rc4_engine	= new RC4Engine();

    		CipherParameters	params = new KeyParameter(key_spec.getEncoded());

    		rc4_engine.init( mode == Cipher.ENCRYPT_MODE, params );
    	}

    	//System.out.println( "RC4 key: " + ByteFormatter.encodeString( key_spec.getEncoded()));

   			// skip first 1024 bytes of stream to protected against a Fluhrer, Mantin and Shamir attack

    	byte[]	temp = new byte[1024];

    	temp = update( temp );

    	//System.out.println( "RC4: first discard = " + ByteFormatter.encodeString( temp, 0, 4 ));
    }else{

    	cipher = Cipher.getInstance( algorithm );

    	cipher.init( mode, key_spec );
    }
}
 
Example 10
Source File: TransportCipher.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
TransportCipher(
	String					algorithm,
	int						mode,
	SecretKeySpec			key_spec )

	throws Exception
{
    if ( algorithm.equals( "RC4" )){

    	if ( !internal_rc4 ){

    		try{
    	    	cipher = Cipher.getInstance( algorithm );

    	    	cipher.init( mode, key_spec );

    		}catch( Throwable e ){

    			internal_rc4	= true;
    		}
    	}

    	if ( internal_rc4 ){

    		rc4_engine	= new RC4Engine();

    		CipherParameters	params = new KeyParameter(key_spec.getEncoded());

    		rc4_engine.init( mode == Cipher.ENCRYPT_MODE, params );
    	}

    	//System.out.println( "RC4 key: " + ByteFormatter.encodeString( key_spec.getEncoded()));

   			// skip first 1024 bytes of stream to protected against a Fluhrer, Mantin and Shamir attack

    	byte[]	temp = new byte[1024];

    	temp = update( temp );

    	//System.out.println( "RC4: first discard = " + ByteFormatter.encodeString( temp, 0, 4 ));
    }else{

    	cipher = Cipher.getInstance( algorithm );

    	cipher.init( mode, key_spec );
    }
}