use of javax.crypto.Cipher in project sling by apache.
the class TopologyRequestValidator method decrypt.
/**
* Decrypt the body.
*
* @param jsonArray the encrypted payload
* @return the decrypted payload.
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws InvalidAlgorithmParameterException
* @throws JSONException
*/
private String decrypt(JsonArray jsonArray) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, getCiperKey(Base64.decodeBase64(jsonArray.getString(0).getBytes("UTF-8"))), new IvParameterSpec(Base64.decodeBase64(jsonArray.getString(1).getBytes("UTF-8"))));
return new String(cipher.doFinal(Base64.decodeBase64(jsonArray.getString(2).getBytes("UTF-8"))));
}
use of javax.crypto.Cipher in project robovm by robovm.
the class CipherInputStreamTest method testSkip.
public void testSkip() throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
InputStream in = new CipherInputStream(new ByteArrayInputStream(cipherText), cipher);
assertTrue(in.skip(5) > 0);
}
use of javax.crypto.Cipher in project robovm by robovm.
the class CipherInputStreamTest method testCipherInputStream_TruncatedInput_Failure.
public void testCipherInputStream_TruncatedInput_Failure() throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(new byte[16], "AES"), new IvParameterSpec(new byte[16]));
InputStream is = new CipherInputStream(new ByteArrayInputStream(new byte[31]), cipher);
is.read(new byte[4]);
is.close();
}
use of javax.crypto.Cipher in project robovm by robovm.
the class CipherTest method testCipher_updateAAD_AfterInit_Failure.
public void testCipher_updateAAD_AfterInit_Failure() throws Exception {
Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[128 / 8], "AES"));
try {
c.updateAAD((byte[]) null);
fail("should not be able to call updateAAD with null input");
} catch (IllegalArgumentException expected) {
}
try {
c.updateAAD((ByteBuffer) null);
fail("should not be able to call updateAAD with null input");
} catch (IllegalArgumentException expected) {
}
try {
c.updateAAD(null, 0, 8);
fail("should not be able to call updateAAD with null input");
} catch (IllegalArgumentException expected) {
}
try {
c.updateAAD(new byte[8], -1, 7);
fail("should not be able to call updateAAD with invalid offset");
} catch (IllegalArgumentException expected) {
}
try {
c.updateAAD(new byte[8], 0, -1);
fail("should not be able to call updateAAD with negative length");
} catch (IllegalArgumentException expected) {
}
try {
c.updateAAD(new byte[8], 0, 8 + 1);
fail("should not be able to call updateAAD with too large length");
} catch (IllegalArgumentException expected) {
}
}
use of javax.crypto.Cipher in project robovm by robovm.
the class ServerHandshakeImpl method unwrap.
/**
* Proceses inbound handshake messages
* @param bytes
*/
@Override
public void unwrap(byte[] bytes) {
io_stream.append(bytes);
while (io_stream.available() > 0) {
int handshakeType;
int length;
io_stream.mark();
try {
handshakeType = io_stream.read();
length = io_stream.readUint24();
if (io_stream.available() < length) {
io_stream.reset();
return;
}
switch(handshakeType) {
case // CLIENT_HELLO
1:
if (clientHello != null && this.status != FINISHED) {
// Client hello has been received during handshake
unexpectedMessage();
return;
}
// if protocol planed to send Hello Request message
// - cancel this demand.
needSendHelloRequest = false;
clientHello = new ClientHello(io_stream, length);
if (nonBlocking) {
delegatedTasks.add(new DelegatedTask(new Runnable() {
public void run() {
processClientHello();
}
}, this));
return;
}
processClientHello();
break;
case // CLIENT CERTIFICATE
11:
if (isResuming || certificateRequest == null || serverHelloDone == null || clientCert != null) {
unexpectedMessage();
return;
}
clientCert = new CertificateMessage(io_stream, length);
if (clientCert.certs.length == 0) {
if (parameters.getNeedClientAuth()) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE: no client certificate received");
}
} else {
String authType = clientCert.getAuthType();
try {
parameters.getTrustManager().checkClientTrusted(clientCert.certs, authType);
} catch (CertificateException e) {
fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Untrusted Client Certificate ", e);
}
session.peerCertificates = clientCert.certs;
}
break;
case // CERTIFICATE_VERIFY
15:
if (isResuming || clientKeyExchange == null || clientCert == null || //client certificate
clientKeyExchange.isEmpty() || // parameters
certificateVerify != null || changeCipherSpecReceived) {
unexpectedMessage();
return;
}
certificateVerify = new CertificateVerify(io_stream, length);
String authType = clientCert.getAuthType();
DigitalSignature ds = new DigitalSignature(authType);
ds.init(clientCert.certs[0]);
byte[] md5_hash = null;
byte[] sha_hash = null;
if ("RSA".equals(authType)) {
md5_hash = io_stream.getDigestMD5withoutLast();
sha_hash = io_stream.getDigestSHAwithoutLast();
} else if ("DSA".equals(authType)) {
sha_hash = io_stream.getDigestSHAwithoutLast();
// The Signature should be empty in case of anonymous signature algorithm:
// } else if ("DH".equals(authType)) {
}
ds.setMD5(md5_hash);
ds.setSHA(sha_hash);
if (!ds.verifySignature(certificateVerify.signedHash)) {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
}
break;
case // CLIENT_KEY_EXCHANGE
16:
if (isResuming || serverHelloDone == null || clientKeyExchange != null || (clientCert == null && parameters.getNeedClientAuth())) {
unexpectedMessage();
return;
}
if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, true);
Cipher c = null;
try {
c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.UNWRAP_MODE, privKey);
preMasterSecret = c.unwrap(clientKeyExchange.exchange_keys, "preMasterSecret", Cipher.SECRET_KEY).getEncoded();
// check preMasterSecret:
if (preMasterSecret.length != 48 || preMasterSecret[0] != clientHello.client_version[0] || preMasterSecret[1] != clientHello.client_version[1]) {
// incorrect preMasterSecret
// prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
preMasterSecret = new byte[48];
parameters.getSecureRandom().nextBytes(preMasterSecret);
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
} else {
// diffie hellman key exchange
clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, false);
if (clientKeyExchange.isEmpty()) {
// TODO check that client cert. DH params
// matched server cert. DH params
// client cert. contains fixed DH parameters
preMasterSecret = ((DHPublicKey) clientCert.certs[0].getPublicKey()).getY().toByteArray();
} else {
try {
KeyFactory kf = KeyFactory.getInstance("DH");
KeyAgreement agreement = KeyAgreement.getInstance("DH");
PublicKey clientPublic = kf.generatePublic(new DHPublicKeySpec(new BigInteger(1, clientKeyExchange.exchange_keys), serverKeyExchange.par1, serverKeyExchange.par2));
agreement.init(privKey);
agreement.doPhase(clientPublic, true);
preMasterSecret = agreement.generateSecret();
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
return;
}
}
}
computerMasterSecret();
break;
case // FINISHED
20:
if (!isResuming && !changeCipherSpecReceived) {
unexpectedMessage();
return;
}
clientFinished = new Finished(io_stream, length);
verifyFinished(clientFinished.getData());
session.context = parameters.getServerSessionContext();
parameters.getServerSessionContext().putSession(session);
if (!isResuming) {
sendChangeCipherSpec();
} else {
session.lastAccessedTime = System.currentTimeMillis();
status = FINISHED;
}
break;
default:
unexpectedMessage();
return;
}
} catch (IOException e) {
// io stream dosn't contain complete handshake message
io_stream.reset();
return;
}
}
}
Aggregations