Search in sources :

Example 81 with SecretKey

use of javax.crypto.SecretKey in project azure-sdk-for-java by Azure.

the class AesValidationTests method getAes.

private static JsonWebKey getAes() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(TRANSFORMATION);
    keyGen.init(256);
    SecretKey skey = keyGen.generateKey();
    return JsonWebKey.fromAes(skey);
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 82 with SecretKey

use of javax.crypto.SecretKey in project chassis by Kixeye.

the class WebSocketTransportTest method testWebSocketServiceWithJsonWithPskEncryption.

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");
    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);
    WebSocketClient wsClient = new WebSocketClient();
    try {
        context.refresh();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);
        messageRegistry.registerType("stuff", TestObject.class);
        wsClient.start();
        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, context.getBean(WebSocketPskFrameProcessor.class));
        Session session = wsClient.connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())).get(5000, TimeUnit.MILLISECONDS);
        Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);
        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));
        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        envelope = new Envelope("getStuff", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        response = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));
        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);
        envelope = new Envelope("expectedError", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);
        envelope = new Envelope("unexpectedError", null, null, null);
        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC");
        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));
        error = webSocket.getResponse(5, TimeUnit.SECONDS);
        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}
Also used : ServiceError(com.kixeye.chassis.transport.dto.ServiceError) HashMap(java.util.HashMap) WebSocketMessageRegistry(com.kixeye.chassis.transport.websocket.WebSocketMessageRegistry) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) Envelope(com.kixeye.chassis.transport.dto.Envelope) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) URI(java.net.URI) SecretKey(javax.crypto.SecretKey) Header(com.kixeye.chassis.transport.dto.Header) MapPropertySource(org.springframework.core.env.MapPropertySource) QueuingWebSocketListener(com.kixeye.chassis.transport.websocket.QueuingWebSocketListener) KeyGenerator(javax.crypto.KeyGenerator) WebSocketPskFrameProcessor(com.kixeye.chassis.transport.websocket.WebSocketPskFrameProcessor) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) StandardEnvironment(org.springframework.core.env.StandardEnvironment) Session(org.eclipse.jetty.websocket.api.Session) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) Test(org.junit.Test)

Example 83 with SecretKey

use of javax.crypto.SecretKey in project Gradle-demo by Arisono.

the class HmacEncoder method getKey.

/**
     * 根据给定密钥生成算法创建密钥
     *
     * @param algorithm 密钥算法
     * @return 密钥
     * @throws RuntimeException 当 {@link NoSuchAlgorithmException} 发生时
     */
public byte[] getKey() {
    // 初始化KeyGenerator
    KeyGenerator keyGenerator = null;
    try {
        keyGenerator = KeyGenerator.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage());
    }
    // 产生密钥
    SecretKey secretKey = keyGenerator.generateKey();
    // 获得密钥
    return secretKey.getEncoded();
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyGenerator(javax.crypto.KeyGenerator)

Example 84 with SecretKey

use of javax.crypto.SecretKey in project Gradle-demo by Arisono.

the class AESUtil method encryptAES.

/**
	 * 加密
	 * @throws Exception 
	 */
public static byte[] encryptAES(byte[] data, byte[] key) throws Exception {
    //恢复密钥
    SecretKey secretKey = new SecretKeySpec(key, "AES");
    //Cipher完成加密
    Cipher cipher = Cipher.getInstance("AES");
    //根据密钥对cipher进行初始化
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    //加密
    byte[] encrypt = cipher.doFinal(data);
    return encrypt;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher)

Example 85 with SecretKey

use of javax.crypto.SecretKey in project Gradle-demo by Arisono.

the class AESUtil method initKey.

/**
	 * 生成密钥
	 * @throws Exception 
	 */
public static byte[] initKey() throws Exception {
    //密钥生成器
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    //初始化密钥生成器
    //默认128,获得无政策权限后可用192或256
    keyGen.init(128);
    //生成密钥
    SecretKey secretKey = keyGen.generateKey();
    return secretKey.getEncoded();
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

SecretKey (javax.crypto.SecretKey)491 Cipher (javax.crypto.Cipher)176 SecretKeySpec (javax.crypto.spec.SecretKeySpec)141 KeyGenerator (javax.crypto.KeyGenerator)121 SecretKeyFactory (javax.crypto.SecretKeyFactory)89 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 SecureRandom (java.security.SecureRandom)61 InvalidKeyException (java.security.InvalidKeyException)58 PBEKeySpec (javax.crypto.spec.PBEKeySpec)58 IvParameterSpec (javax.crypto.spec.IvParameterSpec)46 IOException (java.io.IOException)44 Test (org.junit.Test)40 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)35 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)34 KeyStore (java.security.KeyStore)32 PrivateKey (java.security.PrivateKey)30 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)30 KeyStoreException (java.security.KeyStoreException)29 BadPaddingException (javax.crypto.BadPaddingException)29 Mac (javax.crypto.Mac)29