Java Examples for java.security.AlgorithmParameters
The following java examples will help you to understand the usage of java.security.AlgorithmParameters. These source code samples are taken from different open source projects.
Example 1
| Project: j2objc-master File: DisabledAlgorithmConstraints.java View source code |
@Override
public final boolean permits(Set<CryptoPrimitive> primitives, String algorithm, AlgorithmParameters parameters) {
if (algorithm == null || algorithm.length() == 0) {
throw new IllegalArgumentException("No algorithm name specified");
}
if (primitives == null || primitives.isEmpty()) {
throw new IllegalArgumentException("No cryptographic primitive specified");
}
Set<String> elements = null;
for (String disabled : disabledAlgorithms) {
if (disabled == null || disabled.isEmpty()) {
continue;
}
// check the full name
if (disabled.equalsIgnoreCase(algorithm)) {
return false;
}
// decompose the algorithm into sub-elements
if (elements == null) {
elements = decomposes(algorithm);
}
// check the items of the algorithm
for (String element : elements) {
if (disabled.equalsIgnoreCase(element)) {
return false;
}
}
}
return true;
}Example 2
| Project: bc-java-master File: JcaTlsCrypto.java View source code |
private boolean checkCurve(int namedCurve) {
String curveName = NamedCurve.getNameOfSpecificCurve(namedCurve);
if (curveName == null) {
return false;
}
if (namedCurve < supportedCurveIDs.length && supportedCurveIDs[namedCurve] != null) {
return supportedCurveIDs[namedCurve].booleanValue();
}
try {
AlgorithmParameters params = this.getHelper().createAlgorithmParameters("EC");
params.init(new ECGenParameterSpec(curveName));
boolean supported = params.getParameterSpec(ECParameterSpec.class) != null;
if (namedCurve < supportedCurveIDs.length) {
supportedCurveIDs[namedCurve] = Boolean.valueOf(supported);
}
return supported;
} catch (Exception e) {
supportedCurveIDs[namedCurve] = Boolean.valueOf(false);
return false;
}
}Example 3
| Project: irma_future_id-master File: RSATest.java View source code |
public void performTest() throws Exception {
KeyFactory fact;
byte[] input = new byte[] { (byte) 0x54, (byte) 0x85, (byte) 0x9b, (byte) 0x34, (byte) 0x2c, (byte) 0x49, (byte) 0xea, (byte) 0x2a };
byte[][] output = new byte[][] { Hex.decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"), Hex.decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"), Hex.decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"), Hex.decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"), Hex.decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"), Hex.decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"), Hex.decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"), Hex.decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"), Hex.decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c") };
SecureRandom rand = new FixedSecureRandom();
fact = KeyFactory.getInstance("RSA", "BC");
PrivateKey privKey = fact.generatePrivate(privKeySpec);
PublicKey pubKey = fact.generatePublic(pubKeySpec);
PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);
//
// No Padding
//
Cipher c = Cipher.getInstance("RSA", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
byte[] out = c.doFinal(input);
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - incremental
//
c = Cipher.getInstance("RSA", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.update(input);
out = c.doFinal();
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - incremental - explicit use of NONE in mode.
//
c = Cipher.getInstance("RSA/NONE/NoPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.update(input);
out = c.doFinal();
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - maximum length
//
c = Cipher.getInstance("RSA", "BC");
byte[] modBytes = ((RSAPublicKey) pubKey).getModulus().toByteArray();
byte[] maxInput = new byte[modBytes.length - 1];
maxInput[0] |= 0x7f;
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(maxInput);
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, maxInput)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(maxInput)) + " got " + new String(Hex.encode(out)));
}
//
// PKCS1 V 1.5
//
c = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[1])) {
fail("PKCS1 test failed on encrypt expected " + new String(Hex.encode(output[1])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("PKCS1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// PKCS1 V 1.5 - NONE
//
c = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[1])) {
fail("PKCS1 test failed on encrypt expected " + new String(Hex.encode(output[1])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("PKCS1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// OAEP - SHA1
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[2])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
AlgorithmParameters oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-1 parameters");
}
//
// OAEP - SHA224
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA224AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[3])) {
fail("OAEP SHA-224 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-224 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-224 parameters");
}
//
// OAEP - SHA 256
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[4])) {
fail("OAEP SHA-256 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-256 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-256 parameters");
}
//
// OAEP - SHA 384
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA384AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[5])) {
fail("OAEP SHA-384 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-384 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-384 parameters");
}
//
// OAEP - MD5
//
c = Cipher.getInstance("RSA/NONE/OAEPWithMD5AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[6])) {
fail("OAEP MD5 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP MD5 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default md5 parameters");
}
//
// OAEP - SHA1 with default parameters
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand);
out = c.doFinal(input);
if (!areEqual(out, output[2])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 })) {
fail("OAEP test failed default parameters");
}
//
// OAEP - SHA1 with specified string
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand);
out = c.doFinal(input);
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE)), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[] { 1, 2, 3, 4, 5 }))).getEncoded())) {
fail("OAEP test failed changed sha-1 parameters");
}
if (!areEqual(out, output[7])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey, oaepP);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// ISO9796-1
//
byte[] isoInput = Hex.decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec);
PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec);
c = Cipher.getInstance("RSA/NONE/ISO9796-1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, isoPrivKey);
out = c.doFinal(isoInput);
if (!areEqual(out, output[8])) {
fail("ISO9796-1 test failed on encrypt expected " + new String(Hex.encode(output[3])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, isoPubKey);
out = c.doFinal(out);
if (!areEqual(out, isoInput)) {
fail("ISO9796-1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
//
// generation with parameters test.
//
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
//
// 768 bit RSA with e = 2^16-1
//
keyPairGen.initialize(new RSAKeyGenParameterSpec(768, BigInteger.valueOf(65537)), new SecureRandom());
KeyPair kp = keyPairGen.generateKeyPair();
pubKey = kp.getPublic();
privKey = kp.getPrivate();
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("key generation test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// comparison check
//
KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) keyFact.translateKey(privKey);
if (!privKey.equals(crtKey)) {
fail("private key equality check failed");
}
crtKey = (RSAPrivateCrtKey) keyFact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
if (!privKey.equals(crtKey)) {
fail("private key equality check failed");
}
crtKey = (RSAPrivateCrtKey) serializeDeserialize(privKey);
if (!privKey.equals(crtKey)) {
fail("private key equality check failed");
}
if (privKey.hashCode() != crtKey.hashCode()) {
fail("private key hashCode check failed");
}
RSAPublicKey copyKey = (RSAPublicKey) keyFact.translateKey(pubKey);
if (!pubKey.equals(copyKey)) {
fail("public key equality check failed");
}
copyKey = (RSAPublicKey) keyFact.generatePublic(new X509EncodedKeySpec(pubKey.getEncoded()));
if (!pubKey.equals(copyKey)) {
fail("public key equality check failed");
}
copyKey = (RSAPublicKey) serializeDeserialize(pubKey);
if (!pubKey.equals(copyKey)) {
fail("public key equality check failed");
}
if (pubKey.hashCode() != copyKey.hashCode()) {
fail("public key hashCode check failed");
}
//
// test an OAEP key
//
SubjectPublicKeyInfo oaepKey = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, new RSAESOAEPparams()), SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()).parsePublicKey());
copyKey = (RSAPublicKey) serializeDeserialize(keyFact.generatePublic(new X509EncodedKeySpec(oaepKey.getEncoded())));
if (!pubKey.equals(copyKey)) {
fail("public key equality check failed");
}
if (pubKey.hashCode() != copyKey.hashCode()) {
fail("public key hashCode check failed");
}
if (!Arrays.areEqual(copyKey.getEncoded(), oaepKey.getEncoded())) {
fail("encoding does not match");
}
oaepCompatibilityTest("SHA-1", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-224", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-256", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-384", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-512", priv2048Key, pub2048Key);
SecureRandom random = new SecureRandom();
rawModeTest("SHA1withRSA", X509ObjectIdentifiers.id_SHA1, priv2048Key, pub2048Key, random);
rawModeTest("MD5withRSA", PKCSObjectIdentifiers.md5, priv2048Key, pub2048Key, random);
rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.ripemd128, priv2048Key, pub2048Key, random);
// init reset test
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.update(new byte[40]);
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.update(new byte[40]);
}Example 4
| Project: oobd-master File: PEMReader.java View source code |
public Object parseObject(PemObject obj) throws IOException {
try {
EncryptedPrivateKeyInfo info = EncryptedPrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(obj.getContent()));
AlgorithmIdentifier algId = info.getEncryptionAlgorithm();
if (pFinder == null) {
throw new PEMException("no PasswordFinder specified");
}
if (PEMUtilities.isPKCS5Scheme2(algId.getAlgorithm())) {
PBES2Parameters params = PBES2Parameters.getInstance(algId.getParameters());
KeyDerivationFunc func = params.getKeyDerivationFunc();
EncryptionScheme scheme = params.getEncryptionScheme();
PBKDF2Params defParams = (PBKDF2Params) func.getParameters();
int iterationCount = defParams.getIterationCount().intValue();
byte[] salt = defParams.getSalt();
String algorithm = scheme.getAlgorithm().getId();
SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algorithm, pFinder.getPassword(), salt, iterationCount);
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
AlgorithmParameters algParams = AlgorithmParameters.getInstance(algorithm, symProvider);
algParams.init(scheme.getParameters().toASN1Primitive().getEncoded());
cipher.init(Cipher.DECRYPT_MODE, key, algParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getPrivateKeyAlgorithm().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else if (PEMUtilities.isPKCS12(algId.getAlgorithm())) {
PKCS12PBEParams params = PKCS12PBEParams.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getIV(), params.getIterations().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else if (PEMUtilities.isPKCS5Scheme1(algId.getAlgorithm())) {
PBEParameter params = PBEParameter.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getSalt(), params.getIterationCount().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else {
throw new PEMException("Unknown algorithm: " + algId.getAlgorithm());
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new PEMException("problem parsing ENCRYPTED PRIVATE KEY: " + e.toString(), e);
}
}Example 5
| Project: android-15-master File: CipherTest.java View source code |
public void test_initWithKeyAlgorithmParameters() throws Exception {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[8];
sr.nextBytes(iv);
AlgorithmParameterSpec ap = new IvParameterSpec(iv);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
assertNotNull(c.getParameters());
try {
c.init(Cipher.DECRYPT_MODE, cipherKey, ap);
fail();
} catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, cipherKeyDES, (AlgorithmParameters) null);
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
}Example 6
| Project: android-libcore64-master File: CipherTest.java View source code |
public void test_initWithKeyAlgorithmParameters() throws Exception {
AlgorithmParameterSpec ap = new IvParameterSpec(IV);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, ap);
assertNotNull(c.getParameters());
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_3DES, ap);
fail();
} catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, (AlgorithmParameters) null);
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
}Example 7
| Project: android-sdk-sources-for-api-level-23-master File: CipherTest.java View source code |
public void test_initWithKeyAlgorithmParameters() throws Exception {
AlgorithmParameterSpec ap = new IvParameterSpec(IV);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, ap);
assertNotNull(c.getParameters());
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_3DES, ap);
fail();
} catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, (AlgorithmParameters) null);
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
}Example 8
| Project: android_libcore-master File: JCEBlockCipher.java View source code |
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (pbeSpec != null) { try { engineParams = AlgorithmParameters.getInstance(pbeAlgorithm, "BC"); engineParams.init(pbeSpec); } catch (Exception e) { return null; } } else if (ivParam != null) { String name = cipher.getUnderlyingCipher().getAlgorithmName(); if (name.indexOf('/') >= 0) { name = name.substring(0, name.indexOf('/')); } try { engineParams = AlgorithmParameters.getInstance(name, "BC"); engineParams.init(ivParam.getIV()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
Example 9
| Project: android_platform_libcore-master File: CipherTest.java View source code |
public void test_initWithKeyAlgorithmParameters() throws Exception {
AlgorithmParameterSpec ap = new IvParameterSpec(IV);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, ap);
assertNotNull(c.getParameters());
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_3DES, ap);
fail();
} catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, (AlgorithmParameters) null);
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
}Example 10
| Project: ARTPart-master File: CipherTest.java View source code |
public void test_initWithKeyAlgorithmParameters() throws Exception {
AlgorithmParameterSpec ap = new IvParameterSpec(IV);
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, ap);
assertNotNull(c.getParameters());
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_3DES, ap);
fail();
} catch (InvalidKeyException expected) {
}
try {
c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, (AlgorithmParameters) null);
fail();
} catch (InvalidAlgorithmParameterException expected) {
}
}Example 11
| Project: property-db-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 12
| Project: robovm-master File: OpenSSLCipher.java View source code |
@Override protected AlgorithmParameters engineGetParameters() { if (iv != null && iv.length > 0) { try { AlgorithmParameters params = AlgorithmParameters.getInstance(getBaseCipherName()); params.init(iv); return params; } catch (NoSuchAlgorithmException e) { return null; } catch (IOException e) { return null; } } return null; }
Example 13
| Project: atlas-lb-master File: RSATest.java View source code |
public void performTest() throws Exception {
KeyFactory fact;
byte[] input = new byte[] { (byte) 0x54, (byte) 0x85, (byte) 0x9b, (byte) 0x34, (byte) 0x2c, (byte) 0x49, (byte) 0xea, (byte) 0x2a };
byte[][] output = new byte[][] { Hex.decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"), Hex.decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"), Hex.decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"), Hex.decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"), Hex.decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"), Hex.decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"), Hex.decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"), Hex.decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"), Hex.decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c") };
SecureRandom rand = new FixedSecureRandom();
fact = KeyFactory.getInstance("RSA", "BC");
PrivateKey privKey = fact.generatePrivate(privKeySpec);
PublicKey pubKey = fact.generatePublic(pubKeySpec);
PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);
//
// No Padding
//
Cipher c = Cipher.getInstance("RSA", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
byte[] out = c.doFinal(input);
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - incremental
//
c = Cipher.getInstance("RSA", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.update(input);
out = c.doFinal();
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - incremental - explicit use of NONE in mode.
//
c = Cipher.getInstance("RSA/NONE/NoPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.update(input);
out = c.doFinal();
if (!areEqual(out, output[0])) {
fail("NoPadding test failed on encrypt expected " + new String(Hex.encode(output[0])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// No Padding - maximum length
//
c = Cipher.getInstance("RSA", "BC");
byte[] modBytes = ((RSAPublicKey) pubKey).getModulus().toByteArray();
byte[] maxInput = new byte[modBytes.length - 1];
maxInput[0] |= 0x7f;
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(maxInput);
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, maxInput)) {
fail("NoPadding test failed on decrypt expected " + new String(Hex.encode(maxInput)) + " got " + new String(Hex.encode(out)));
}
//
// PKCS1 V 1.5
//
c = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[1])) {
fail("PKCS1 test failed on encrypt expected " + new String(Hex.encode(output[1])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("PKCS1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// PKCS1 V 1.5 - NONE
//
c = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[1])) {
fail("PKCS1 test failed on encrypt expected " + new String(Hex.encode(output[1])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("PKCS1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// OAEP - SHA1
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[2])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
AlgorithmParameters oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-1 parameters");
}
//
// OAEP - SHA224
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA224AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[3])) {
fail("OAEP SHA-224 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-224 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-224 parameters");
}
//
// OAEP - SHA 256
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[4])) {
fail("OAEP SHA-256 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-256 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-256 parameters");
}
//
// OAEP - SHA 384
//
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA384AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pub2048Key, rand);
out = c.doFinal(input);
if (!areEqual(out, output[5])) {
fail("OAEP SHA-384 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, priv2048Key);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP SHA-384 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default sha-384 parameters");
}
//
// OAEP - MD5
//
c = Cipher.getInstance("RSA/NONE/OAEPWithMD5AndMGF1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
if (!areEqual(out, output[6])) {
fail("OAEP MD5 test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP MD5 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(PKCSObjectIdentifiers.md5, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[0]))).getEncoded())) {
fail("OAEP test failed default md5 parameters");
}
//
// OAEP - SHA1 with default parameters
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand);
out = c.doFinal(input);
if (!areEqual(out, output[2])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 })) {
fail("OAEP test failed default parameters");
}
//
// OAEP - SHA1 with specified string
//
c = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");
c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand);
out = c.doFinal(input);
oaepP = c.getParameters();
if (!areEqual(oaepP.getEncoded(), new RSAESOAEPparams(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(new byte[] { 1, 2, 3, 4, 5 }))).getEncoded())) {
fail("OAEP test failed changed sha-1 parameters");
}
if (!areEqual(out, output[7])) {
fail("OAEP test failed on encrypt expected " + new String(Hex.encode(output[2])) + " got " + new String(Hex.encode(out)));
}
c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
c.init(Cipher.DECRYPT_MODE, privKey, oaepP);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("OAEP test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// ISO9796-1
//
byte[] isoInput = Hex.decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec);
PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec);
c = Cipher.getInstance("RSA/NONE/ISO9796-1Padding", "BC");
c.init(Cipher.ENCRYPT_MODE, isoPrivKey);
out = c.doFinal(isoInput);
if (!areEqual(out, output[8])) {
fail("ISO9796-1 test failed on encrypt expected " + new String(Hex.encode(output[3])) + " got " + new String(Hex.encode(out)));
}
c.init(Cipher.DECRYPT_MODE, isoPubKey);
out = c.doFinal(out);
if (!areEqual(out, isoInput)) {
fail("ISO9796-1 test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
//
// generation with parameters test.
//
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
//
// 768 bit RSA with e = 2^16-1
//
keyPairGen.initialize(new RSAKeyGenParameterSpec(768, BigInteger.valueOf(65537)), new SecureRandom());
KeyPair kp = keyPairGen.generateKeyPair();
pubKey = kp.getPublic();
privKey = kp.getPrivate();
c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
out = c.doFinal(input);
c.init(Cipher.DECRYPT_MODE, privKey);
out = c.doFinal(out);
if (!areEqual(out, input)) {
fail("key generation test failed on decrypt expected " + new String(Hex.encode(input)) + " got " + new String(Hex.encode(out)));
}
//
// comparison check
//
KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) keyFact.translateKey(privKey);
if (!privKey.equals(crtKey)) {
fail("private key equality check failed");
}
RSAPublicKey copyKey = (RSAPublicKey) keyFact.translateKey(pubKey);
if (!pubKey.equals(copyKey)) {
fail("public key equality check failed");
}
oaepCompatibilityTest("SHA-1", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-224", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-256", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-384", priv2048Key, pub2048Key);
oaepCompatibilityTest("SHA-512", priv2048Key, pub2048Key);
SecureRandom random = new SecureRandom();
rawModeTest("SHA1withRSA", X509ObjectIdentifiers.id_SHA1, priv2048Key, pub2048Key, random);
rawModeTest("MD5withRSA", PKCSObjectIdentifiers.md5, priv2048Key, pub2048Key, random);
rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.ripemd128, priv2048Key, pub2048Key, random);
}Example 14
| Project: bugvm-master File: OpenSSLCipher.java View source code |
@Override protected AlgorithmParameters engineGetParameters() { if (iv != null && iv.length > 0) { try { AlgorithmParameters params = AlgorithmParameters.getInstance(getBaseCipherName()); params.init(iv); return params; } catch (NoSuchAlgorithmException e) { return null; } catch (IOException e) { return null; } } return null; }
Example 15
| Project: openmonitor-android-agent-master File: DiffieHellmanValues.java View source code |
/**
* Generates and returns {@link DHParameterSpec}.
*
*
@return {@link String}
*
@see AlgorithmParameters
*
@see AlgorithmParameterGenerator
*/
public static DHParameterSpec generateDiffieHellmanValues() throws NoSuchAlgorithmException, InvalidParameterSpecException {
AlgorithmParameterGenerator parameterGenerator = AlgorithmParameterGenerator.getInstance("DH");
parameterGenerator.init(1024);
AlgorithmParameters parameters = parameterGenerator.generateParameters();
return (DHParameterSpec) parameters.getParameterSpec(DHParameterSpec.class);
}Example 16
| Project: QRCode-APG-master File: PKCS10CertificationRequest.java View source code |
private void setSignatureParameters(Signature signature, DEREncodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
if (params != null && !DERNull.INSTANCE.equals(params)) {
AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider());
try {
sigParams.init(params.getDERObject().getDEREncoded());
} catch (IOException e) {
throw new SignatureException("IOException decoding parameters: " + e.getMessage());
}
if (signature.getAlgorithm().endsWith("MGF1")) {
try {
signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
} catch (GeneralSecurityException e) {
throw new SignatureException("Exception extracting parameters: " + e.getMessage());
}
}
}
}Example 17
| Project: RipplePower-master File: PKCS10CertificationRequest.java View source code |
private void setSignatureParameters(Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
if (params != null && !DERNull.INSTANCE.equals(params)) {
AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider());
try {
sigParams.init(params.toASN1Primitive().getEncoded(ASN1Encoding.DER));
} catch (IOException e) {
throw new SignatureException("IOException decoding parameters: " + e.getMessage());
}
if (signature.getAlgorithm().endsWith("MGF1")) {
try {
signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
} catch (GeneralSecurityException e) {
throw new SignatureException("Exception extracting parameters: " + e.getMessage());
}
}
}
}Example 18
| Project: thundernetwork-master File: ECDH.java View source code |
/*
* Quite some mess here to have all objects with the correct types...
*/
public static ECDHKeySet getSharedSecret(ECKey keyServer, ECKey keyClient) {
try {
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "SunEC");
parameters.init(new ECGenParameterSpec("secp256k1"));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint().getYCoord().toBigInteger()), ecParameters);
KeyFactory kf = KeyFactory.getInstance("EC");
ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);
JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);
new ECKey().getKeyCrypter();
KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
aKeyAgree.init(ecPrivKey);
aKeyAgree.doPhase(ecPubKey, true);
return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
} catch (Exception e) {
throw new RuntimeException(e);
}
// MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
//
// return hash.digest();
}Example 19
| Project: wildfly-elytron-master File: PasswordBasedEncryptionUtil.java View source code |
private static AlgorithmParameters generateAlgorithmParameters(String algorithm, int iterationCount, byte[] salt, IvParameterSpec ivSpec, Provider provider) throws GeneralSecurityException { AlgorithmParameters tempParams = provider == null ? AlgorithmParameters.getInstance(algorithm) : AlgorithmParameters.getInstance(algorithm, provider); PBEParameterSpec pbeParameterSpec = ivSpec != null ? new PBEParameterSpec(salt, iterationCount, ivSpec) : new PBEParameterSpec(salt, iterationCount); tempParams.init(pbeParameterSpec); return tempParams; }
Example 20
| Project: wildfly-security-master File: PasswordBasedEncryptionUtil.java View source code |
private static AlgorithmParameters generateAlgorithmParameters(String algorithm, int iterationCount, byte[] salt, IvParameterSpec ivSpec, Provider provider) throws GeneralSecurityException { AlgorithmParameters tempParams = provider == null ? AlgorithmParameters.getInstance(algorithm) : AlgorithmParameters.getInstance(algorithm, provider); PBEParameterSpec pbeParameterSpec = ivSpec != null ? new PBEParameterSpec(salt, iterationCount, ivSpec) : new PBEParameterSpec(salt, iterationCount); tempParams.init(pbeParameterSpec); return tempParams; }
Example 21
| Project: jdk7u-jdk-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 22
| Project: ManagedRuntimeInitiative-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 23
| Project: open-mika-master File: X509Certificate.java View source code |
/**
* Parse a DER stream into an X.509 certificate.
*
* @param encoded The encoded bytes.
*/
private void parse(InputStream encoded) throws Exception {
DERReader der = new DERReader(encoded);
// Certificate ::= SEQUENCE {
DERValue cert = der.read();
// GRU rm: logger.log (Component.X509, "start Certificate len == {0}",
// GRU rm: new Integer (cert.getLength()));
this.encoded = cert.getEncoded();
if (!cert.isConstructed()) {
throw new IOException("malformed Certificate");
}
// TBSCertificate ::= SEQUENCE {
DERValue tbsCert = der.read();
if (tbsCert.getValue() != DER.CONSTRUCTED_VALUE) {
throw new IOException("malformed TBSCertificate");
}
tbsCertBytes = tbsCert.getEncoded();
// GRU rm: logger.log (Component.X509, "start TBSCertificate len == {0}",
// GRU rm: new Integer (tbsCert.getLength()));
// Version ::= INTEGER [0] { v1(0), v2(1), v3(2) }
DERValue val = der.read();
if (val.getTagClass() == DER.CONTEXT && val.getTag() == 0) {
version = ((BigInteger) der.read().getValue()).intValue() + 1;
val = der.read();
} else {
version = 1;
}
// GRU rm: logger.log (Component.X509, "read version == {0}",
// GRU rm: new Integer (version));
// SerialNumber ::= INTEGER
serialNo = (BigInteger) val.getValue();
// GRU rm: logger.log (Component.X509, "read serial number == {0}", serialNo);
// AlgorithmIdentifier ::= SEQUENCE {
val = der.read();
if (!val.isConstructed()) {
throw new IOException("malformed AlgorithmIdentifier");
}
int certAlgLen = val.getLength();
// GRU rm: logger.log (Component.X509, "start AlgorithmIdentifier len == {0}",
// GRU rm: new Integer (certAlgLen));
val = der.read();
// algorithm OBJECT IDENTIFIER,
algId = (OID) val.getValue();
// parameters ANY DEFINED BY algorithm OPTIONAL }
if (certAlgLen > val.getEncodedLength()) {
val = der.read();
if (val == null) {
algVal = null;
} else {
algVal = val.getEncoded();
if (val.isConstructed())
encoded.skip(val.getLength());
}
// GRU rm: logger.log (Component.X509, "read algorithm parameters == {0}", algVal);
}
// issuer Name,
val = der.read();
issuer = new X500DistinguishedName(val.getEncoded());
der.skip(val.getLength());
// notAfter Time }
if (!der.read().isConstructed()) {
throw new IOException("malformed Validity");
}
notBefore = (Date) der.read().getValue();
// GRU rm: logger.log (Component.X509, "read notBefore == {0}", notBefore);
notAfter = (Date) der.read().getValue();
// GRU rm: logger.log (Component.X509, "read notAfter == {0}", notAfter);
// subject Name,
val = der.read();
subject = new X500DistinguishedName(val.getEncoded());
der.skip(val.getLength());
// GRU rm: logger.log (Component.X509, "read subject == {0}", subject);
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DERValue spki = der.read();
if (!spki.isConstructed()) {
throw new IOException("malformed SubjectPublicKeyInfo");
}
KeyFactory spkFac = KeyFactory.getInstance("X.509");
subjectKey = spkFac.generatePublic(new X509EncodedKeySpec(spki.getEncoded()));
der.skip(spki.getLength());
if (version > 1) {
val = der.read();
}
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 1) {
byte[] b = (byte[]) val.getValue();
issuerUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
// GRU rm: logger.log (Component.X509, "read issuerUniqueId == {0}", issuerUniqueId);
val = der.read();
}
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 2) {
byte[] b = (byte[]) val.getValue();
subjectUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
// GRU rm: logger.log (Component.X509, "read subjectUniqueId == {0}", subjectUniqueId);
val = der.read();
}
if (version >= 3 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 3) {
val = der.read();
// GRU rm: logger.log (Component.X509, "start Extensions len == {0}",
// GRU rm: new Integer (val.getLength()));
int len = 0;
while (len < val.getLength()) {
DERValue ext = der.read();
// GRU rm: logger.log (Component.X509, "start extension len == {0}",
// GRU rm: new Integer (ext.getLength()));
Extension e = new Extension(ext.getEncoded());
extensions.put(e.getOid(), e);
der.skip(ext.getLength());
len += ext.getEncodedLength();
// GRU rm: logger.log (Component.X509, "read extension {0} == {1}",
// GRU rm: new Object[] { e.getOid (), e });
// GRU rm: logger.log (Component.X509, "count == {0}", new Integer (len));
}
val = der.read();
}
// GRU rm: logger.log (Component.X509, "read value {0}", val);
if (!val.isConstructed()) {
throw new CertificateException("malformed AlgorithmIdentifier");
}
int sigAlgLen = val.getLength();
// GRU rm: logger.log (Component.X509, "start AlgorithmIdentifier len == {0}",
// GRU rm: new Integer (sigAlgLen));
val = der.read();
while (val != null && !(val.getValue() instanceof OID)) {
val = der.read();
}
sigAlgId = (OID) val.getValue();
// GRU rm: logger.log (Component.X509, "read algorithm id == {0}", sigAlgId);
if (sigAlgLen > val.getEncodedLength()) {
val = der.read();
if (val.getValue() == null) {
if (subjectKey instanceof DSAPublicKey) {
AlgorithmParameters params = AlgorithmParameters.getInstance("DSA");
DSAParams dsap = ((DSAPublicKey) subjectKey).getParams();
DSAParameterSpec spec = new DSAParameterSpec(dsap.getP(), dsap.getQ(), dsap.getG());
params.init(spec);
sigAlgVal = params.getEncoded();
}
} else {
sigAlgVal = val.getEncoded();
}
if (val.isConstructed()) {
encoded.skip(val.getLength());
}
// GRU rm: logger.log (Component.X509, "read parameters == {0}", sigAlgVal);
}
signature = ((BitString) der.read().getValue()).toByteArray();
// GRU rm: logger.log (Component.X509, "read signature ==\n{0}", Util.hexDump(signature, ">>>> "));
}Example 24
| Project: amazon-cognito-developer-authentication-sample-master File: AESEncryption.java View source code |
private static byte[] encrypt(String clearText, String key, byte[] iv) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params);
return cipher.doFinal(clearText.getBytes());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to encrypt.", e);
}
}Example 25
| Project: browserprint-master File: SampleIDs.java View source code |
/**
* Encrypt an integer to a String.
*
* @param integer
* @param context
* @return
* @throws ServletException
*/
private static String encryptInteger(Integer integer, ServletContext context) throws ServletException {
/* Get password. */
String password = context.getInitParameter("SampleSetIDEncryptionPassword");
/* Generate salt. */
SecureRandom rand = new SecureRandom();
byte salt[] = new byte[8];
rand.nextBytes(salt);
byte[] iv;
byte[] ciphertext;
try {
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Encrypt the SampleSetID. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ciphertext = cipher.doFinal(ByteBuffer.allocate(4).putInt(integer).array());
} catch (Exception ex) {
throw new ServletException(ex);
}
/* Store the encrypted SampleSetID in a cookie */
Encoder encoder = Base64.getEncoder();
String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
return encryptedStr;
}Example 26
| Project: CameraV-master File: AesUtility.java View source code |
public static String EncryptToKey(SecretKey secret_key, String message) {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secret_key);
AlgorithmParameters params = cipher.getParameters();
String iv = Base64.encodeToString(params.getParameterSpec(IvParameterSpec.class).getIV(), Base64.DEFAULT);
String new_message = Base64.encodeToString(cipher.doFinal(message.getBytes("UTF-8")), Base64.DEFAULT);
JSONObject pack = new JSONObject();
pack.put(Codes.Keys.IV, iv);
pack.put(Codes.Keys.VALUE, new_message);
return pack.toString();
} catch (IllegalBlockSizeException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (BadPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidKeyException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
}
return null;
}Example 27
| Project: informa-master File: AesUtility.java View source code |
public static String EncryptToKey(SecretKey secret_key, String message) {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secret_key);
AlgorithmParameters params = cipher.getParameters();
String iv = Base64.encodeToString(params.getParameterSpec(IvParameterSpec.class).getIV(), Base64.DEFAULT);
String new_message = Base64.encodeToString(cipher.doFinal(message.getBytes("UTF-8")), Base64.DEFAULT);
JSONObject pack = new JSONObject();
pack.put(Codes.Keys.IV, iv);
pack.put(Codes.Keys.VALUE, new_message);
return pack.toString();
} catch (IllegalBlockSizeException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (BadPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidKeyException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
}
return null;
}Example 28
| Project: InformaCore-master File: AesUtility.java View source code |
public static String EncryptToKey(SecretKey secret_key, String message) {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secret_key);
AlgorithmParameters params = cipher.getParameters();
String iv = Base64.encodeToString(params.getParameterSpec(IvParameterSpec.class).getIV(), Base64.DEFAULT);
String new_message = Base64.encodeToString(cipher.doFinal(message.getBytes("UTF-8")), Base64.DEFAULT);
JSONObject pack = new JSONObject();
pack.put(Codes.Keys.IV, iv);
pack.put(Codes.Keys.VALUE, new_message);
return pack.toString();
} catch (IllegalBlockSizeException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (BadPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (NoSuchPaddingException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidKeyException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
}
return null;
}Example 29
| Project: kodex-master File: AbstractCryptoService.java View source code |
/*
* (non-Javadoc)
* @see com.kryptnostic.kodex.v1.crypto.ciphers.CryptoService#encrypt(byte[], byte[])
*/
@Override
public BlockCiphertext encrypt(byte[] bytes, byte[] salt) throws SecurityConfigurationException {
try {
SecretKeySpec secretKeySpec = getSecretKeySpec(salt);
Cipher cipher = cypher.getInstance();
byte[] iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
AlgorithmParameters params = cipher.getParameters();
if (params == null) {
iv = Cyphers.generateSalt(cypher.getKeySize() >>> 3);
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
} catch (InvalidAlgorithmParameterException e) {
throw new SecurityConfigurationException(e);
}
} else {
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
}
byte[] encryptedBytes = cipher.doFinal(bytes);
return new BlockCiphertext(iv, salt, encryptedBytes);
} catch (NoSuchAlgorithmException e) {
throw new SecurityConfigurationException(e);
} catch (InvalidKeySpecException e) {
throw new SecurityConfigurationException(e);
} catch (IllegalBlockSizeException e) {
throw new SecurityConfigurationException(e);
} catch (BadPaddingException e) {
throw new SecurityConfigurationException(e);
} catch (NoSuchPaddingException e) {
throw new SecurityConfigurationException(e);
} catch (InvalidKeyException e) {
throw new SecurityConfigurationException(e);
} catch (InvalidParameterSpecException e) {
throw new SecurityConfigurationException(e);
}
}Example 30
| Project: leshan-master File: LeshanServerDemo.java View source code |
public static void createAndStartServer(int webPort, String localAddress, int localPort, String secureLocalAddress, int secureLocalPort, String modelsFolderPath, String redisUrl, String keyStorePath, String keyStoreType, String keyStorePass, String keyStoreAlias, String keyStoreAliasPass) throws Exception {
// Prepare LWM2M server
LeshanServerBuilder builder = new LeshanServerBuilder();
builder.setLocalAddress(localAddress, localPort);
builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
builder.setEncoder(new DefaultLwM2mNodeEncoder());
LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
builder.setDecoder(decoder);
builder.setNetworkConfig(NetworkConfig.getStandard());
// connect to redis if needed
Pool<Jedis> jedis = null;
if (redisUrl != null) {
// TODO: support sentinel pool and make pool configurable
jedis = new JedisPool(new URI(redisUrl));
}
PublicKey publicKey = null;
// Set up X.509 mode
if (keyStorePath != null) {
try {
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
try (FileInputStream fis = new FileInputStream(keyStorePath)) {
keyStore.load(fis, keyStorePass == null ? null : keyStorePass.toCharArray());
List<Certificate> trustedCertificates = new ArrayList<>();
for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
if (keyStore.isCertificateEntry(alias)) {
trustedCertificates.add(keyStore.getCertificate(alias));
} else if (keyStore.isKeyEntry(alias) && alias.equals(keyStoreAlias)) {
List<X509Certificate> x509CertificateChain = new ArrayList<>();
Certificate[] certificateChain = keyStore.getCertificateChain(alias);
if (certificateChain == null || certificateChain.length == 0) {
LOG.error("Keystore alias must have a non-empty chain of X509Certificates.");
System.exit(-1);
}
for (Certificate certificate : certificateChain) {
if (!(certificate instanceof X509Certificate)) {
LOG.error("Non-X.509 certificate in alias chain is not supported: {}", certificate);
System.exit(-1);
}
x509CertificateChain.add((X509Certificate) certificate);
}
Key key = keyStore.getKey(alias, keyStoreAliasPass == null ? new char[0] : keyStoreAliasPass.toCharArray());
if (!(key instanceof PrivateKey)) {
LOG.error("Keystore alias must have a PrivateKey entry, was {}", key == null ? null : key.getClass().getName());
System.exit(-1);
}
builder.setPrivateKey((PrivateKey) key);
publicKey = keyStore.getCertificate(alias).getPublicKey();
builder.setCertificateChain(x509CertificateChain.toArray(new X509Certificate[x509CertificateChain.size()]));
}
}
builder.setTrustedCertificates(trustedCertificates.toArray(new Certificate[trustedCertificates.size()]));
}
} catch (KeyStoreExceptionIOException | e) {
LOG.error("Unable to initialize X.509.", e);
System.exit(-1);
}
} else // Otherwise, set up RPK mode
{
try {
// Get point values
byte[] publicX = Hex.decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
byte[] publicY = Hex.decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
byte[] privateS = Hex.decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray());
// Get Elliptic Curve Parameter spec for secp256r1
AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
algoParameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
// Create key specs
KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec);
KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);
// Get keys
publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
PrivateKey privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
builder.setPublicKey(publicKey);
builder.setPrivateKey(privateKey);
} catch (InvalidKeySpecExceptionNoSuchAlgorithmException | InvalidParameterSpecException | e) {
LOG.error("Unable to initialize RPK.", e);
System.exit(-1);
}
}
// Define model provider
List<ObjectModel> models = ObjectLoader.loadDefault();
models.addAll(ObjectLoader.loadDdfResources("/models/", modelPaths));
if (modelsFolderPath != null) {
models.addAll(ObjectLoader.loadObjectsFromDir(new File(modelsFolderPath)));
}
LwM2mModelProvider modelProvider = new StaticModelProvider(models);
builder.setObjectModelProvider(modelProvider);
// Set securityStore & registrationStore
EditableSecurityStore securityStore;
if (jedis == null) {
// use file persistence
securityStore = new FileSecurityStore();
} else {
// use Redis Store
securityStore = new RedisSecurityStore(jedis);
builder.setRegistrationStore(new RedisRegistrationStore(jedis));
}
builder.setSecurityStore(securityStore);
// Create and start LWM2M server
LeshanServer lwServer = builder.build();
// Now prepare Jetty
Server server = new Server(webPort);
WebAppContext root = new WebAppContext();
root.setContextPath("/");
root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
root.setParentLoaderPriority(true);
server.setHandler(root);
// Create Servlet
EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort());
ServletHolder eventServletHolder = new ServletHolder(eventServlet);
root.addServlet(eventServletHolder, "/event/*");
ServletHolder clientServletHolder = new ServletHolder(new ClientServlet(lwServer, lwServer.getSecureAddress().getPort()));
root.addServlet(clientServletHolder, "/api/clients/*");
ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
root.addServlet(securityServletHolder, "/api/security/*");
ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet(lwServer.getModelProvider()));
root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");
// Start Jetty & Leshan
lwServer.start();
server.start();
LOG.info("Web server started at {}.", server.getURI());
}Example 31
| Project: LimeWire-Pirate-Edition-master File: CipherProviderImpl.java View source code |
public byte[] decrypt(byte[] ciphertext, Key key, CipherType cipherType) throws IOException {
Cipher cipher;
try {
cipher = Cipher.getInstance(cipherType.getDescription());
AlgorithmParameters algParams = cipher.getParameters();
cipher.init(Cipher.DECRYPT_MODE, key, algParams);
} catch (GeneralSecurityException ex) {
throw IOUtils.getIOException("Security exception while initializing: ", ex);
}
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
CipherInputStream cin = new CipherInputStream(in, cipher);
byte[] buffer = new byte[8];
int bytesRead;
while ((bytesRead = cin.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
in.close();
cin.close();
return out.toByteArray();
}Example 32
| Project: limewire5-ruby-master File: CipherProviderImpl.java View source code |
public byte[] decrypt(byte[] ciphertext, Key key, CipherType cipherType) throws IOException {
Cipher cipher;
try {
cipher = Cipher.getInstance(cipherType.getDescription());
AlgorithmParameters algParams = cipher.getParameters();
cipher.init(Cipher.DECRYPT_MODE, key, algParams);
} catch (GeneralSecurityException ex) {
throw IOUtils.getIOException("Security exception while initializing: ", ex);
}
InputStream in = new ByteArrayInputStream(ciphertext);
ByteArrayOutputStream out = new ByteArrayOutputStream();
CipherInputStream cin = new CipherInputStream(in, cipher);
byte[] buffer = new byte[8];
int bytesRead;
while ((bytesRead = cin.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
in.close();
cin.close();
return out.toByteArray();
}Example 33
| Project: openjdk-master File: PKCS11Test.java View source code |
static List<ECParameterSpec> getKnownCurves(Provider p) throws Exception {
int index;
int begin;
int end;
String curve;
List<ECParameterSpec> results = new ArrayList<>();
String kcProp = Security.getProvider("SunEC").getProperty("AlgorithmParameters.EC SupportedCurves");
if (kcProp == null) {
throw new RuntimeException("\"AlgorithmParameters.EC SupportedCurves property\" not found");
}
System.out.println("Finding supported curves using list from SunEC\n");
index = 0;
for (; ; ) {
begin = kcProp.indexOf('[', index);
end = kcProp.indexOf(']', index);
if (begin == -1 || end == -1) {
break;
}
index = end + 1;
begin++;
end = kcProp.indexOf(',', begin);
if (end == -1) {
end = index - 1;
}
curve = kcProp.substring(begin, end);
ECParameterSpec e = getECParameterSpec(p, curve);
System.out.print("\t " + curve + ": ");
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
kpg.initialize(e);
kpg.generateKeyPair();
results.add(e);
System.out.println("Supported");
} catch (ProviderException ex) {
System.out.println("Unsupported: PKCS11: " + ex.getCause().getMessage());
} catch (InvalidAlgorithmParameterException ex) {
System.out.println("Unsupported: Key Length: " + ex.getMessage());
}
}
if (results.size() == 0) {
throw new RuntimeException("No supported EC curves found");
}
return results;
}Example 34
| Project: openjdk8-jdk-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 35
| Project: reinvent2013-mobile-photo-share-master File: AESEncryption.java View source code |
private static byte[] encrypt(String clearText, String key, byte[] iv) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params);
return cipher.doFinal(clearText.getBytes());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to encrypt.", e);
}
}Example 36
| Project: sakai-cle-master File: SimpleEncryption.java View source code |
public static String encrypt(String key, String source) {
if (source == null) {
return null;
}
byte[] salt = new byte[8];
new Random().nextBytes(salt);
char[] password = key.toCharArray();
try {
SecretKey secret = generateSecret(password, salt);
/* Encrypt the message. */
Cipher cipher = Cipher.getInstance(CIPHER);
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(source.getBytes("UTF-8"));
// Pack the byte arrays into a string hex encoded.
StringBuffer out = new StringBuffer();
out.append(ShaUtil.byteToHex(salt));
out.append(":");
out.append(ShaUtil.byteToHex(iv));
out.append(":");
out.append(ShaUtil.byteToHex(ciphertext));
out.append(":");
out.append(CIPHER);
return out.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 37
| Project: tika-master File: CryptoParser.java View source code |
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
try {
Cipher cipher;
if (provider != null) {
cipher = Cipher.getInstance(transformation, provider);
} else {
cipher = Cipher.getInstance(transformation);
}
Key key = context.get(Key.class);
if (key == null) {
throw new EncryptedDocumentException("No decryption key provided");
}
AlgorithmParameters params = context.get(AlgorithmParameters.class);
SecureRandom random = context.get(SecureRandom.class);
if (params != null && random != null) {
cipher.init(Cipher.DECRYPT_MODE, key, params, random);
} else if (params != null) {
cipher.init(Cipher.DECRYPT_MODE, key, params);
} else if (random != null) {
cipher.init(Cipher.DECRYPT_MODE, key, random);
} else {
cipher.init(Cipher.DECRYPT_MODE, key);
}
super.parse(new CipherInputStream(stream, cipher), handler, metadata, context);
} catch (GeneralSecurityException e) {
throw new TikaException("Unable to decrypt document stream", e);
}
}Example 38
| Project: XobotOS-master File: PEMReader.java View source code |
public Object parseObject(PemObject obj) throws IOException {
try {
EncryptedPrivateKeyInfo info = EncryptedPrivateKeyInfo.getInstance(ASN1Object.fromByteArray(obj.getContent()));
AlgorithmIdentifier algId = info.getEncryptionAlgorithm();
if (pFinder == null) {
throw new PEMException("no PasswordFinder specified");
}
if (PEMUtilities.isPKCS5Scheme2(algId.getAlgorithm())) {
PBES2Parameters params = PBES2Parameters.getInstance(algId.getParameters());
KeyDerivationFunc func = params.getKeyDerivationFunc();
EncryptionScheme scheme = params.getEncryptionScheme();
PBKDF2Params defParams = (PBKDF2Params) func.getParameters();
int iterationCount = defParams.getIterationCount().intValue();
byte[] salt = defParams.getSalt();
String algorithm = scheme.getAlgorithm().getId();
SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algorithm, pFinder.getPassword(), salt, iterationCount);
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
AlgorithmParameters algParams = AlgorithmParameters.getInstance(algorithm, symProvider);
algParams.init(scheme.getParameters().getDERObject().getEncoded());
cipher.init(Cipher.DECRYPT_MODE, key, algParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else if (PEMUtilities.isPKCS12(algId.getAlgorithm())) {
PKCS12PBEParams params = PKCS12PBEParams.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getIV(), params.getIterations().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else if (PEMUtilities.isPKCS5Scheme1(algId.getAlgorithm())) {
PBEParameter params = PBEParameter.getInstance(algId.getParameters());
String algorithm = algId.getAlgorithm().getId();
PBEKeySpec pbeSpec = new PBEKeySpec(pFinder.getPassword());
SecretKeyFactory secKeyFact = SecretKeyFactory.getInstance(algorithm, symProvider);
PBEParameterSpec defParams = new PBEParameterSpec(params.getSalt(), params.getIterationCount().intValue());
Cipher cipher = Cipher.getInstance(algorithm, symProvider);
cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Object.fromByteArray(cipher.doFinal(info.getEncryptedData())));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pInfo.getEncoded());
KeyFactory keyFact = KeyFactory.getInstance(pInfo.getAlgorithmId().getAlgorithm().getId(), asymProvider);
return keyFact.generatePrivate(keySpec);
} else {
throw new PEMException("Unknown algorithm: " + algId.getAlgorithm());
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new PEMException("problem parsing ENCRYPTED PRIVATE KEY: " + e.toString(), e);
}
}Example 39
| Project: barchart-udt-master File: DSAParameterGenerator.java View source code |
/**
* Generates the parameters.
*
* @return the new AlgorithmParameters object
*/
protected AlgorithmParameters engineGenerateParameters() {
AlgorithmParameters algParams = null;
try {
if (this.random == null) {
this.random = new SecureRandom();
}
BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
BigInteger paramP = pAndQ[0];
BigInteger paramQ = pAndQ[1];
BigInteger paramG = generateG(paramP, paramQ);
DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP, paramQ, paramG);
algParams = AlgorithmParameters.getInstance("DSA", "SUN");
algParams.init(dsaParamSpec);
} catch (InvalidParameterSpecException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchProviderException e) {
throw new RuntimeException(e.getMessage());
}
return algParams;
}Example 40
| Project: classlib6-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 41
| Project: ikvm-openjdk-master File: SealedObject.java View source code |
private Object unseal(Key key, String provider) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
/*
* Create the parameter object.
*/
AlgorithmParameters params = null;
if (this.encodedParams != null) {
try {
if (provider != null)
params = AlgorithmParameters.getInstance(this.paramsAlg, provider);
else
params = AlgorithmParameters.getInstance(this.paramsAlg);
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.paramsAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
params.init(this.encodedParams);
}
/*
* Create and initialize the cipher.
*/
Cipher c;
try {
if (provider != null)
c = Cipher.getInstance(this.sealAlg, provider);
else
c = Cipher.getInstance(this.sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException("Padding that was used in " + "sealing operation not " + "available");
} catch (NoSuchProviderException nspe) {
if (provider == null) {
throw new NoSuchAlgorithmException(this.sealAlg + " not found");
} else {
throw new NoSuchProviderException(nspe.getMessage());
}
}
try {
if (params != null)
c.init(Cipher.DECRYPT_MODE, key, params);
else
c.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidAlgorithmParameterException iape) {
throw new RuntimeException(iape.getMessage());
}
/*
* Unseal the object
*/
byte[] content = c.doFinal(this.encryptedContent);
/*
* De-serialize it
*/
// creating a stream pipe-line, from b to a
ByteArrayInputStream b = new ByteArrayInputStream(content);
ObjectInput a = new extObjectInputStream(b);
try {
Object obj = a.readObject();
return obj;
} finally {
a.close();
}
}Example 42
| Project: JamVM-PH-master File: CipherAdapter.java View source code |
protected AlgorithmParameters engineGetParameters() { byte[] iv = (byte[]) attributes.get(IMode.IV); int cipherBlockSize = cipher.currentBlockSize(); BlockCipherParameterSpec spec = new BlockCipherParameterSpec(iv, cipherBlockSize, keyLen); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("BlockCipherParameters"); params.init(spec); } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidParameterSpecException ipse) { return null; } return params; }
Example 43
| Project: java_to_cpp-master File: BlockCipher.java View source code |
protected final AlgorithmParameters engineGetParameters() { AlgorithmParameterSpec aps = padding.getParamSpec(); if (aps == null) return (AlgorithmParameters) null; // Fix the parameters AlgorithmParameters ap = null; try { ap = AlgorithmParameters.getInstance(algorithm, "CryptixCrypto"); ap.init(aps); } catch (InvalidParameterSpecException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } catch (NoSuchProviderException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } return ap; }
Example 44
| Project: magma-master File: GeneratedSecretKeyDatasourceEncryptionStrategy.java View source code |
@Override
public DatasourceCipherFactory createDatasourceCipherFactory(Datasource ds) {
// If there's already a secret key in the datasource, then stop. We cannot read the contents.
if (ds.hasAttribute(CipherAttributeConstants.SECRET_KEY)) {
throw new MagmaCryptRuntimeException("Datasource '" + ds.getName() + "' is encrypted and cannot be read without the proper decryption key.");
}
try {
String transformation = getTransformation();
SecretKey sk = getSecretKey(ds);
AlgorithmParameters parameters = initialiseParameters(ds, transformation, sk);
return new DefaultDatasourceCipherFactory(transformation, sk, parameters);
} catch (GeneralSecurityExceptionIOException | e) {
throw new MagmaRuntimeException(e);
}
}Example 45
| Project: netevents-master File: AESSocketWrapper.java View source code |
@Override
public SocketChannel wrapSocket(SocketChannel chan) throws IOException {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), SALT, ITER_COUNT, KEY_LEN);
SecretKey secretKey = factory.generateSecret(spec);
Key key = new SecretKeySpec(secretKey.getEncoded(), "AES");
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(new byte[16]));
return new CryptSocketChannel(chan, key, params);
} catch (NoSuchAlgorithmExceptionInvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | InvalidParameterSpecException | e) {
throw new IOException(e);
}
}Example 46
| Project: oxAuth-master File: AbstractCryptoProvider.java View source code |
public PublicKey getPublicKey(String alias, JSONObject jwks) throws Exception {
java.security.PublicKey publicKey = null;
JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
for (int i = 0; i < webKeys.length(); i++) {
JSONObject key = webKeys.getJSONObject(i);
if (alias.equals(key.getString(KEY_ID))) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(key.getString(ALGORITHM));
if (signatureAlgorithm != null) {
if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.RSA)) {
publicKey = new RSAPublicKeyImpl(new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
} else if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.EC)) {
AlgorithmParameters parameters = AlgorithmParameters.getInstance(SignatureAlgorithmFamily.EC);
parameters.init(new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
publicKey = KeyFactory.getInstance(SignatureAlgorithmFamily.EC).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))), ecParameters));
}
}
}
}
return publicKey;
}Example 47
| Project: phoneme-components-cdc-master File: DSAParameterGenerator.java View source code |
/**
* Generates the parameters.
*
* @return the new AlgorithmParameters object
*/
protected AlgorithmParameters engineGenerateParameters() {
AlgorithmParameters algParams = null;
try {
if (this.random == null) {
this.random = new SecureRandom();
}
BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
BigInteger paramP = pAndQ[0];
BigInteger paramQ = pAndQ[1];
BigInteger paramG = generateG(paramP, paramQ);
DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP, paramQ, paramG);
algParams = AlgorithmParameters.getInstance("DSA", "SUN");
algParams.init(dsaParamSpec);
} catch (InvalidParameterSpecException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
} catch (NoSuchProviderException e) {
throw new RuntimeException(e.getMessage());
}
return algParams;
}Example 48
| Project: picketbox-master File: TestJCE.java View source code |
static void testKey() throws Exception {
int size = 8 * 24;
KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
kgen.init(size);
SecretKey key = kgen.generateKey();
byte[] kbytes = key.getEncoded();
System.out.println("key.Algorithm = " + key.getAlgorithm());
System.out.println("key.Format = " + key.getFormat());
System.out.println("key.Encoded Size = " + kbytes.length);
Cipher cipher = Cipher.getInstance("Blowfish");
AlgorithmParameters params = cipher.getParameters();
System.out.println("Blowfish.params = " + params);
cipher.init(Cipher.ENCRYPT_MODE, key);
SealedObject msg = new SealedObject("This is a secret", cipher);
SecretKeySpec serverKey = new SecretKeySpec(kbytes, "Blowfish");
Cipher scipher = Cipher.getInstance("Blowfish");
scipher.init(Cipher.DECRYPT_MODE, serverKey);
String theMsg = (String) msg.getObject(scipher);
System.out.println("Decrypted: " + theMsg);
SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG");
BigInteger bi = new BigInteger(320, rnd);
byte[] k2bytes = bi.toByteArray();
SecretKeySpec keySpec = new SecretKeySpec(k2bytes, "Blowfish");
System.out.println("key2.Algorithm = " + key.getAlgorithm());
System.out.println("key2.Format = " + key.getFormat());
System.out.println("key2.Encoded Size = " + kbytes.length);
System.out.println("keySpec.Algorithm = " + keySpec.getAlgorithm());
System.out.println("keySpec.Format = " + keySpec.getFormat());
}Example 49
| Project: picketlink-master File: RSA_OAEP_256.java View source code |
/**
* Encrypts the specified Content Encryption Key (CEK).
*
* @param pub The public RSA key. Must not be {@code null}.
* @param cek The Content Encryption Key (CEK) to encrypt. Must not be {@code null}.
*
* @return The encrypted Content Encryption Key (CEK).
*
* @throws RuntimeException If encryption failed.
*/
public static byte[] encryptCEK(final RSAPublicKey pub, final SecretKey cek) {
try {
AlgorithmParameters algp = AlgorithmParameters.getInstance("OAEP", new BouncyCastleProvider());
AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
algp.init(paramSpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", new BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, pub, algp);
return cipher.doFinal(cek.getEncoded());
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}Example 50
| Project: PixelKnot-master File: Aes.java View source code |
public static Map<String, String> EncryptWithPassword(String password, String message, byte[] salt) {
Map<String, String> pack = null;
String new_message = null;
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret_key = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
// TODO: follow up (https://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html)
cipher.init(Cipher.ENCRYPT_MODE, secret_key);
AlgorithmParameters params = cipher.getParameters();
String iv = Base64.encodeToString(params.getParameterSpec(IvParameterSpec.class).getIV(), Base64.DEFAULT);
new_message = Base64.encodeToString(cipher.doFinal(message.getBytes("UTF-8")), Base64.DEFAULT);
pack = new HashMap<String, String>();
pack.put(iv, new_message);
} catch (IllegalBlockSizeException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (BadPaddingException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (InvalidKeySpecException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (NoSuchPaddingException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (InvalidKeyException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
Log.e(Logger.UI, e.toString());
e.printStackTrace();
}
return pack;
}Example 51
| Project: rakam-master File: CryptUtil.java View source code |
public static String encryptAES(String data, String secretKey) {
try {
byte[] secretKeys = Arrays.copyOfRange(Hashing.sha256().hashString(secretKey, Charsets.UTF_8).asBytes(), 0, 16);
final SecretKey secret = new SecretKeySpec(secretKeys, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
final AlgorithmParameters params = cipher.getParameters();
final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
final byte[] cipherText = cipher.doFinal(data.getBytes(Charsets.UTF_8));
return DatatypeConverter.printHexBinary(iv) + DatatypeConverter.printHexBinary(cipherText);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}Example 52
| Project: teiid-designer-master File: DhKeyGenerator.java View source code |
/**
* Can be used to generate new parameters
*/
public static void main(String[] args) throws Exception {
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance(ALGORITHM);
paramGen.init(2048);
AlgorithmParameters params = paramGen.generateParameters();
DHParameterSpec dhSpec = params.getParameterSpec(DHParameterSpec.class);
System.out.println("l=" + dhSpec.getL());
System.out.println("g=" + dhSpec.getG());
System.out.println("p=" + dhSpec.getP());
}Example 53
| Project: uma-master File: AbstractCryptoProvider.java View source code |
public PublicKey getPublicKey(String alias, JSONObject jwks) throws Exception {
java.security.PublicKey publicKey = null;
JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
for (int i = 0; i < webKeys.length(); i++) {
JSONObject key = webKeys.getJSONObject(i);
if (alias.equals(key.getString(KEY_ID))) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(key.getString(ALGORITHM));
if (signatureAlgorithm != null) {
if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.RSA)) {
publicKey = new RSAPublicKeyImpl(new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
} else if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.EC)) {
AlgorithmParameters parameters = AlgorithmParameters.getInstance(SignatureAlgorithmFamily.EC);
parameters.init(new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
publicKey = KeyFactory.getInstance(SignatureAlgorithmFamily.EC).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))), ecParameters));
}
}
}
}
return publicKey;
}Example 54
| Project: xtc-master File: BlockCipher.java View source code |
protected final AlgorithmParameters engineGetParameters() { AlgorithmParameterSpec aps = padding.getParamSpec(); if (aps == null) return (AlgorithmParameters) null; // Fix the parameters AlgorithmParameters ap = null; try { ap = AlgorithmParameters.getInstance(algorithm, "CryptixCrypto"); ap.init(aps); } catch (InvalidParameterSpecException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } catch (NoSuchProviderException e) { throw new RuntimeException("PANIC: Unreachable code reached."); } return ap; }
Example 55
| Project: AcademicTorrents-Downloader-master File: PairingManagerTunnelHandler.java View source code |
protected boolean handleLocalTunnel(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
start();
if (SRP_VERIFIER == null || !active) {
throw (new IOException("Secure pairing is not enabled"));
}
boolean good_request = false;
try {
// remove /pairing/tunnel/
String url = request.getURL().substring(16);
int q_pos = url.indexOf('?');
Map<String, String> args = new HashMap<String, String>();
if (q_pos != -1) {
String args_str = url.substring(q_pos + 1);
String[] bits = args_str.split("&");
for (String arg : bits) {
String[] x = arg.split("=");
if (x.length == 2) {
args.put(x[0].toLowerCase(), x[1]);
}
}
url = url.substring(0, q_pos);
}
if (url.startsWith("create")) {
String ac = args.get("ac");
String sid = args.get("sid");
if (ac == null || sid == null) {
throw (new IOException("Access code or service id missing"));
}
if (!ac.equals(manager.peekAccessCode())) {
throw (new IOException("Invalid access code"));
}
PairedServiceImpl ps = manager.getService(sid);
if (ps == null) {
good_request = true;
throw (new IOException("Service '" + sid + "' not registered"));
}
PairedServiceRequestHandler handler = ps.getHandler();
if (handler == null) {
good_request = true;
throw (new IOException("Service '" + sid + "' has no handler registered"));
}
JSONObject json = new JSONObject();
JSONObject result = new JSONObject();
json.put("result", result);
byte[] ss = new byte[] { SRP_SALT[0], SRP_SALT[1], SRP_SALT[2], SRP_SALT[3] };
long tunnel_id = RandomUtils.nextSecureAbsoluteLong();
String tunnel_name = Base32.encode(ss) + "_" + tunnel_id;
synchronized (local_server_map) {
long diff = SystemTime.getMonotonousTime() - last_local_server_create_time;
if (diff < 5000) {
try {
long sleep = 5000 - diff;
System.out.println("Sleeping for " + sleep + " before starting srp");
Thread.sleep(sleep);
} catch (Throwable e) {
}
}
SRP6Server server = new SRP6Server();
server.init(N_3072, G_3072, SRP_VERIFIER, new SHA256Digest(), RandomUtils.SECURE_RANDOM);
BigInteger B = server.generateServerCredentials();
local_server_map.put(tunnel_name, new Object[] { server, handler, null, null });
last_local_server_create_time = SystemTime.getMonotonousTime();
total_local_servers++;
result.put("srp_salt", Base32.encode(SRP_SALT));
result.put("srp_b", Base32.encode(B.toByteArray()));
Map<String, String> headers = request.getHeaders();
String host = headers.get("host");
// remove port number
int pos = host.lastIndexOf("]");
if (pos != -1) {
// ipv6 literal
host = host.substring(0, pos + 1);
} else {
pos = host.indexOf(':');
if (pos != -1) {
host = host.substring(0, pos);
}
}
String abs_url = request.getAbsoluteURL().toString();
// unfortunately there is some nasty code that uses a configured tracker
// address as the default host
abs_url = UrlUtils.setHost(new URL(abs_url), host).toExternalForm();
pos = abs_url.indexOf("/create");
String tunnel_url = abs_url.substring(0, pos) + "/id/" + tunnel_name;
result.put("url", tunnel_url);
}
response.getOutputStream().write(JSONUtils.encodeToJSON(json).getBytes("UTF-8"));
response.setContentType("application/json; charset=UTF-8");
response.setGZIP(true);
good_request = true;
return (true);
} else if (url.startsWith("id/")) {
String tunnel_name = url.substring(3);
Object[] entry;
synchronized (local_server_map) {
entry = local_server_map.get(tunnel_name);
if (entry == null) {
good_request = true;
throw (new IOException("Unknown tunnel id"));
}
}
String srp_a = args.get("srp_a");
String enc_data = args.get("enc_data");
String enc_iv = args.get("enc_iv");
if (srp_a != null && enc_data != null && enc_iv != null) {
try {
synchronized (local_server_map) {
long diff = SystemTime.getMonotonousTime() - last_local_server_agree_time;
if (diff < 5000) {
try {
long sleep = 5000 - diff;
System.out.println("Sleeping for " + sleep + " before completing srp");
Thread.sleep(sleep);
} catch (Throwable e) {
}
}
}
JSONObject json = new JSONObject();
JSONObject result = new JSONObject();
json.put("result", result);
SRP6Server server = (SRP6Server) entry[0];
BigInteger A = new BigInteger(Base32.decode(srp_a));
BigInteger serverS = server.calculateSecret(A);
byte[] shared_secret = serverS.toByteArray();
Cipher decipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] key = new byte[16];
System.arraycopy(shared_secret, 0, key, 0, 16);
SecretKeySpec secret = new SecretKeySpec(key, "AES");
decipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(Base32.decode(enc_iv)));
byte[] dec = decipher.doFinal(Base32.decode(enc_data));
JSONObject dec_json = (JSONObject) JSONUtils.decodeJSON(new String(dec, "UTF-8"));
String tunnel_url = (String) dec_json.get("url");
if (!tunnel_url.contains(tunnel_name)) {
throw (new IOException("Invalid tunnel url"));
}
String endpoint_url = (String) dec_json.get("endpoint");
entry[2] = secret;
entry[3] = endpoint_url;
result.put("state", "activated");
response.getOutputStream().write(JSONUtils.encodeToJSON(json).getBytes("UTF-8"));
response.setContentType("application/json; charset=UTF-8");
response.setGZIP(true);
good_request = true;
return (true);
} catch (Throwable e) {
throw (new IOException(Debug.getNestedExceptionMessage(e)));
} finally {
last_local_server_agree_time = SystemTime.getMonotonousTime();
}
} else if (args.containsKey("close")) {
synchronized (local_server_map) {
local_server_map.remove(tunnel_name);
}
good_request = true;
return (true);
} else {
PairedServiceRequestHandler request_handler = (PairedServiceRequestHandler) entry[1];
SecretKeySpec secret = (SecretKeySpec) entry[2];
String endpoint_url = (String) entry[3];
if (secret == null) {
throw (new IOException("auth not completed"));
}
byte[] request_data = FileUtil.readInputStreamAsByteArray(request.getInputStream());
try {
byte[] decrypted;
{
byte[] IV = new byte[16];
System.arraycopy(request_data, 0, IV, 0, IV.length);
Cipher decipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
decrypted = decipher.doFinal(request_data, 16, request_data.length - 16);
}
byte[] reply_bytes = request_handler.handleRequest(request.getClientAddress2().getAddress(), endpoint_url, decrypted);
{
Cipher encipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = encipher.getParameters();
byte[] IV = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] enc = encipher.doFinal(reply_bytes);
byte[] rep_bytes = new byte[IV.length + enc.length];
System.arraycopy(IV, 0, rep_bytes, 0, IV.length);
System.arraycopy(enc, 0, rep_bytes, IV.length, enc.length);
response.getOutputStream().write(rep_bytes);
response.setContentType("application/octet-stream");
good_request = true;
return (true);
}
} catch (Throwable e) {
throw (new IOException(Debug.getNestedExceptionMessage(e)));
}
}
}
throw (new IOException("Unknown tunnel operation"));
} finally {
if (!good_request) {
manager.recordRequest("SRP", request.getClientAddress2().getAddress().getHostAddress(), false);
}
}
}Example 56
| Project: android_frameworks_base-master File: AndroidKeyStoreCipherSpiBase.java View source code |
@Override
protected final void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
resetAll();
boolean success = false;
try {
init(opmode, key, random);
initAlgorithmSpecificParameters(params);
ensureKeystoreOperationInitialized();
success = true;
} finally {
if (!success) {
resetAll();
}
}
}Example 57
| Project: BitMate-master File: JDKAlgorithmParameterGenerator.java View source code |
protected AlgorithmParameters engineGenerateParameters() { DHParametersGenerator pGen = new DHParametersGenerator(); if (random != null) { pGen.init(strength, 20, random); } else { pGen.init(strength, 20, new SecureRandom()); } DHParameters p = pGen.generateParameters(); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("DH", "BC"); params.init(new DHParameterSpec(p.getP(), p.getG(), l)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }
Example 58
| Project: DTE-master File: Utilities.java View source code |
public static PrivateKey readPrivateKey(byte[] datos, String algo, char[] password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
PKCS8EncodedKeySpec pkcs8KeySpec = null;
if (password != null) {
EncryptedPrivateKeyInfo ekey = new EncryptedPrivateKeyInfo(datos);
Cipher cip = Cipher.getInstance(ekey.getAlgName());
PBEKeySpec pspec = new PBEKeySpec(password);
SecretKeyFactory skfac = SecretKeyFactory.getInstance(ekey.getAlgName());
Key pbeKey = skfac.generateSecret(pspec);
AlgorithmParameters algParams = ekey.getAlgParameters();
cip.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
pkcs8KeySpec = ekey.getKeySpec(cip);
} else {
pkcs8KeySpec = new PKCS8EncodedKeySpec(datos);
}
KeyFactory rsaKeyFac = KeyFactory.getInstance(algo);
return (PrivateKey) rsaKeyFac.generatePrivate(pkcs8KeySpec);
}Example 59
| Project: frostwire-common-master File: PairingManagerTunnelHandler.java View source code |
protected boolean handleLocalTunnel(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
start();
if (SRP_VERIFIER == null || !active) {
throw (new IOException("Secure pairing is not enabled"));
}
boolean good_request = false;
try {
// remove /pairing/tunnel/
String url = request.getURL().substring(16);
int q_pos = url.indexOf('?');
Map<String, String> args = new HashMap<String, String>();
if (q_pos != -1) {
String args_str = url.substring(q_pos + 1);
String[] bits = args_str.split("&");
for (String arg : bits) {
String[] x = arg.split("=");
if (x.length == 2) {
args.put(x[0].toLowerCase(), x[1]);
}
}
url = url.substring(0, q_pos);
}
if (url.startsWith("create")) {
String ac = args.get("ac");
String sid = args.get("sid");
if (ac == null || sid == null) {
throw (new IOException("Access code or service id missing"));
}
if (!ac.equals(manager.peekAccessCode())) {
throw (new IOException("Invalid access code"));
}
PairedServiceImpl ps = manager.getService(sid);
if (ps == null) {
good_request = true;
throw (new IOException("Service '" + sid + "' not registered"));
}
PairedServiceRequestHandler handler = ps.getHandler();
if (handler == null) {
good_request = true;
throw (new IOException("Service '" + sid + "' has no handler registered"));
}
JSONObject json = new JSONObject();
JSONObject result = new JSONObject();
json.put("result", result);
byte[] ss = new byte[] { SRP_SALT[0], SRP_SALT[1], SRP_SALT[2], SRP_SALT[3] };
long tunnel_id = RandomUtils.nextSecureAbsoluteLong();
String tunnel_name = Base32.encode(ss) + "_" + tunnel_id;
synchronized (local_server_map) {
long diff = SystemTime.getMonotonousTime() - last_local_server_create_time;
if (diff < 5000) {
try {
long sleep = 5000 - diff;
System.out.println("Sleeping for " + sleep + " before starting srp");
Thread.sleep(sleep);
} catch (Throwable e) {
}
}
SRP6Server server = new SRP6Server();
server.init(N_3072, G_3072, SRP_VERIFIER, new SHA256Digest(), RandomUtils.SECURE_RANDOM);
BigInteger B = server.generateServerCredentials();
local_server_map.put(tunnel_name, new Object[] { server, handler, null, null });
last_local_server_create_time = SystemTime.getMonotonousTime();
total_local_servers++;
result.put("srp_salt", Base32.encode(SRP_SALT));
result.put("srp_b", Base32.encode(B.toByteArray()));
Map<String, String> headers = request.getHeaders();
String host = headers.get("host");
// remove port number
int pos = host.lastIndexOf("]");
if (pos != -1) {
// ipv6 literal
host = host.substring(0, pos + 1);
} else {
pos = host.indexOf(':');
if (pos != -1) {
host = host.substring(0, pos);
}
}
String abs_url = request.getAbsoluteURL().toString();
// unfortunately there is some nasty code that uses a configured tracker
// address as the default host
abs_url = UrlUtils.setHost(new URL(abs_url), host).toExternalForm();
pos = abs_url.indexOf("/create");
String tunnel_url = abs_url.substring(0, pos) + "/id/" + tunnel_name;
result.put("url", tunnel_url);
}
response.getOutputStream().write(JSONUtils.encodeToJSON(json).getBytes("UTF-8"));
response.setContentType("application/json; charset=UTF-8");
response.setGZIP(true);
good_request = true;
return (true);
} else if (url.startsWith("id/")) {
String tunnel_name = url.substring(3);
Object[] entry;
synchronized (local_server_map) {
entry = local_server_map.get(tunnel_name);
if (entry == null) {
good_request = true;
throw (new IOException("Unknown tunnel id"));
}
}
String srp_a = args.get("srp_a");
String enc_data = args.get("enc_data");
String enc_iv = args.get("enc_iv");
if (srp_a != null && enc_data != null && enc_iv != null) {
try {
synchronized (local_server_map) {
long diff = SystemTime.getMonotonousTime() - last_local_server_agree_time;
if (diff < 5000) {
try {
long sleep = 5000 - diff;
System.out.println("Sleeping for " + sleep + " before completing srp");
Thread.sleep(sleep);
} catch (Throwable e) {
}
}
}
JSONObject json = new JSONObject();
JSONObject result = new JSONObject();
json.put("result", result);
SRP6Server server = (SRP6Server) entry[0];
BigInteger A = new BigInteger(Base32.decode(srp_a));
BigInteger serverS = server.calculateSecret(A);
byte[] shared_secret = serverS.toByteArray();
Cipher decipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] key = new byte[16];
System.arraycopy(shared_secret, 0, key, 0, 16);
SecretKeySpec secret = new SecretKeySpec(key, "AES");
decipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(Base32.decode(enc_iv)));
byte[] dec = decipher.doFinal(Base32.decode(enc_data));
JSONObject dec_json = (JSONObject) JSONUtils.decodeJSON(new String(dec, "UTF-8"));
String tunnel_url = (String) dec_json.get("url");
if (!tunnel_url.contains(tunnel_name)) {
throw (new IOException("Invalid tunnel url"));
}
String endpoint_url = (String) dec_json.get("endpoint");
entry[2] = secret;
entry[3] = endpoint_url;
result.put("state", "activated");
response.getOutputStream().write(JSONUtils.encodeToJSON(json).getBytes("UTF-8"));
response.setContentType("application/json; charset=UTF-8");
response.setGZIP(true);
good_request = true;
return (true);
} catch (Throwable e) {
throw (new IOException(Debug.getNestedExceptionMessage(e)));
} finally {
last_local_server_agree_time = SystemTime.getMonotonousTime();
}
} else if (args.containsKey("close")) {
synchronized (local_server_map) {
local_server_map.remove(tunnel_name);
}
good_request = true;
return (true);
} else {
PairedServiceRequestHandler request_handler = (PairedServiceRequestHandler) entry[1];
SecretKeySpec secret = (SecretKeySpec) entry[2];
String endpoint_url = (String) entry[3];
if (secret == null) {
throw (new IOException("auth not completed"));
}
byte[] request_data = FileUtil.readInputStreamAsByteArray(request.getInputStream());
try {
byte[] decrypted;
{
byte[] IV = new byte[16];
System.arraycopy(request_data, 0, IV, 0, IV.length);
Cipher decipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
decrypted = decipher.doFinal(request_data, 16, request_data.length - 16);
}
byte[] reply_bytes = request_handler.handleRequest(request.getClientAddress2().getAddress(), endpoint_url, decrypted);
{
Cipher encipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = encipher.getParameters();
byte[] IV = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] enc = encipher.doFinal(reply_bytes);
byte[] rep_bytes = new byte[IV.length + enc.length];
System.arraycopy(IV, 0, rep_bytes, 0, IV.length);
System.arraycopy(enc, 0, rep_bytes, IV.length, enc.length);
response.getOutputStream().write(rep_bytes);
response.setContentType("application/octet-stream");
good_request = true;
return (true);
}
} catch (Throwable e) {
throw (new IOException(Debug.getNestedExceptionMessage(e)));
}
}
}
throw (new IOException("Unknown tunnel operation"));
} finally {
if (!good_request) {
manager.recordRequest("SRP", request.getClientAddress2().getAddress().getHostAddress(), false);
}
}
}Example 60
| Project: haskell-java-parser-master File: SealedObject.java View source code |
/**
* Unseal and deserialize this sealed object with the specified key.
*
* @param key The key to decrypt with.
* @return The original object.
* @throws java.io.IOException If reading fails.
* @throws java.lang.ClassNotFoundException If deserialization fails.
* @throws java.security.InvalidKeyException If the supplied key
* cannot be used to unseal this object.
* @throws java.security.NoSuchAlgorithmException If the algorithm
* used to originally seal this object is not available.
*/
public final Object getObject(Key key) throws IOException, ClassNotFoundException, InvalidKeyException, NoSuchAlgorithmException {
try {
if (sealCipher == null)
sealCipher = Cipher.getInstance(sealAlg);
} catch (NoSuchPaddingException nspe) {
throw new NoSuchAlgorithmException(nspe.getMessage());
}
AlgorithmParameters params = null;
if (encodedParams != null) {
params = AlgorithmParameters.getInstance(paramsAlg);
params.init(encodedParams);
}
try {
sealCipher.init(Cipher.DECRYPT_MODE, key, params);
return unseal();
} catch (InvalidAlgorithmParameterException iape) {
throw new IOException("bad parameters");
} catch (IllegalBlockSizeException ibse) {
throw new IOException("illegal block size");
} catch (BadPaddingException bpe) {
throw new IOException("bad padding");
}
}Example 61
| Project: HsmKeyWrappingExample-master File: WrappedKeySerializationExample.java View source code |
// wrapping operation is performed on the HSM
private static byte[] wrapKeyWithKek(SecretKey hsmKek, byte[] wrappingIv, SecretKey keyToBeWrapped) throws GeneralSecurityException {
Cipher wrappingCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "LunaProvider");
AlgorithmParameters algParams = AlgorithmParameters.getInstance("IV", "LunaProvider");
algParams.init(new IvParameterSpec(wrappingIv));
wrappingCipher.init(Cipher.WRAP_MODE, hsmKek, algParams);
return wrappingCipher.wrap(keyToBeWrapped);
}Example 62
| Project: java_security-master File: ElGamalTest2.java View source code |
/**
* �始化密钥对
* @return Map 甲方密钥的Map
* */
public static Map<String, Object> initKey() throws Exception {
//åŠ å…¥å¯¹BouncyCastle支æŒ?
Security.addProvider(new BouncyCastleProvider());
AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance(KEY_ALGORITHM);
//�始化�数生�器
apg.init(KEY_SIZE);
//生�算法�数
AlgorithmParameters params = apg.generateParameters();
//构建å?‚æ•°æ??æ–™
DHParameterSpec elParams = (DHParameterSpec) params.getParameterSpec(DHParameterSpec.class);
//实例化密钥生�器
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM);
//�始化密钥对生�器
kpg.initialize(elParams, new SecureRandom());
KeyPair keyPair = kpg.generateKeyPair();
//甲方公钥
PublicKey publicKey = keyPair.getPublic();
//甲方�钥
PrivateKey privateKey = keyPair.getPrivate();
//将密钥å˜å‚¨åœ¨mapä¸
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}Example 63
| Project: OneSwarm-master File: JDKAlgorithmParameterGenerator.java View source code |
protected AlgorithmParameters engineGenerateParameters() { DHParametersGenerator pGen = new DHParametersGenerator(); if (random != null) { pGen.init(strength, 20, random); } else { pGen.init(strength, 20, new SecureRandom()); } DHParameters p = pGen.generateParameters(); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("DH", "BC"); params.init(new DHParameterSpec(p.getP(), p.getG(), l)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }
Example 64
| Project: pgjdbc-master File: LazyKeyManager.java View source code |
@Override
public PrivateKey getPrivateKey(String alias) {
RandomAccessFile raf = null;
try {
if (key == null && keyfile != null) {
// The private key must be loaded
if (cert == null) {
// We need the certificate for the algorithm
if (getCertificateChain("user") == null) {
// getCertificateChain failed...
return null;
}
}
try {
// NOSONAR
raf = new RandomAccessFile(new File(keyfile), "r");
} catch (FileNotFoundException ex) {
if (!defaultfile) {
throw ex;
}
return null;
}
byte[] keydata = new byte[(int) raf.length()];
raf.readFully(keydata);
raf.close();
raf = null;
KeyFactory kf = KeyFactory.getInstance(cert[0].getPublicKey().getAlgorithm());
try {
KeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keydata);
key = kf.generatePrivate(pkcs8KeySpec);
} catch (InvalidKeySpecException ex) {
EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(keydata);
Cipher cipher;
try {
cipher = Cipher.getInstance(ePKInfo.getAlgName());
} catch (NoSuchPaddingException npex) {
throw new NoSuchAlgorithmException(npex.getMessage(), npex);
}
PasswordCallback pwdcb = new PasswordCallback(GT.tr("Enter SSL password: "), false);
try {
cbh.handle(new Callback[] { pwdcb });
} catch (UnsupportedCallbackException ucex) {
if ((cbh instanceof LibPQFactory.ConsoleCallbackHandler) && ("Console is not available".equals(ucex.getMessage()))) {
error = new PSQLException(GT.tr("Could not read password for SSL key file, console is not available."), PSQLState.CONNECTION_FAILURE, ucex);
} else {
error = new PSQLException(GT.tr("Could not read password for SSL key file by callbackhandler {0}.", cbh.getClass().getName()), PSQLState.CONNECTION_FAILURE, ucex);
}
return null;
}
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(pwdcb.getPassword());
SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName());
Key pbeKey = skFac.generateSecret(pbeKeySpec);
AlgorithmParameters algParams = ePKInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher);
key = kf.generatePrivate(pkcs8KeySpec);
} catch (GeneralSecurityException ikex) {
error = new PSQLException(GT.tr("Could not decrypt SSL key file {0}.", keyfile), PSQLState.CONNECTION_FAILURE, ikex);
return null;
}
}
}
} catch (IOException ioex) {
if (raf != null) {
try {
raf.close();
} catch (IOException ex) {
}
}
error = new PSQLException(GT.tr("Could not read SSL key file {0}.", keyfile), PSQLState.CONNECTION_FAILURE, ioex);
} catch (NoSuchAlgorithmException ex) {
error = new PSQLException(GT.tr("Could not find a java cryptographic algorithm: {0}.", ex.getMessage()), PSQLState.CONNECTION_FAILURE, ex);
return null;
}
return key;
}Example 65
| Project: platform_frameworks_base-master File: ESTHandler.java View source code |
private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
//Security.addProvider(new BouncyCastleProvider());
Log.d(TAG, "/csrattrs:");
/*
byte[] octets = new byte[octetBuffer.remaining()];
octetBuffer.duplicate().get(octets);
for (byte b : octets) {
System.out.printf("%02x ", b & 0xff);
}
*/
Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : csrs) {
Log.d(TAG, asn1Object.toString());
}
if (csrs.size() != 1) {
throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
}
Asn1Object sequence = csrs.iterator().next();
if (sequence.getClass() != Asn1Constructed.class) {
throw new IOException("Unexpected CSR attribute container: " + sequence);
}
String keyAlgo = null;
Asn1Oid keyAlgoOID = null;
String sigAlgo = null;
String curveName = null;
Asn1Oid pubCrypto = null;
int keySize = -1;
Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
for (Asn1Object child : sequence.getChildren()) {
if (child.getTag() == Asn1Decoder.TAG_OID) {
Asn1Oid oid = (Asn1Oid) child;
OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
if (sigEntry != null) {
sigAlgo = sigEntry.getSigAlgo();
keyAlgoOID = sigEntry.getKeyAlgo();
keyAlgo = OidMappings.getJCEName(keyAlgoOID);
} else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
byte[] tlsUnique = httpHandler.getTLSUnique();
if (tlsUnique != null) {
idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
} else {
Log.w(TAG, "Cannot retrieve TLS unique channel binding");
}
}
} else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
Asn1Oid oid = null;
Set<Asn1Oid> oidValues = new HashSet<>();
List<Asn1Object> values = new ArrayList<>();
for (Asn1Object attributeSeq : child.getChildren()) {
if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
oid = (Asn1Oid) attributeSeq;
} else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
for (Asn1Object value : attributeSeq.getChildren()) {
if (value.getTag() == Asn1Decoder.TAG_OID) {
oidValues.add((Asn1Oid) value);
} else {
values.add(value);
}
}
}
}
if (oid == null) {
throw new IOException("Invalid attribute, no OID");
}
if (oid.equals(OidMappings.sExtensionRequest)) {
for (Asn1Oid subOid : oidValues) {
if (OidMappings.isIDAttribute(subOid)) {
if (subOid.equals(OidMappings.sMAC)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
} else if (subOid.equals(OidMappings.sIMEI)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
} else if (subOid.equals(OidMappings.sMEID)) {
idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
} else if (subOid.equals(OidMappings.sDevID)) {
idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
}
}
}
} else if (OidMappings.getCryptoID(oid) != null) {
pubCrypto = oid;
if (!values.isEmpty()) {
for (Asn1Object value : values) {
if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
keySize = (int) ((Asn1Integer) value).getValue();
}
}
}
if (oid.equals(OidMappings.sAlgo_EC)) {
if (oidValues.isEmpty()) {
throw new IOException("No ECC curve name provided");
}
for (Asn1Oid value : oidValues) {
curveName = OidMappings.getJCEName(value);
if (curveName != null) {
break;
}
}
if (curveName == null) {
throw new IOException("Found no ECC curve for " + oidValues);
}
}
}
}
}
if (keyAlgoOID == null) {
throw new IOException("No public key algorithm specified");
}
if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
throw new IOException("Mismatching key algorithms");
}
if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
if (keySize < MinRSAKeySize) {
if (keySize >= 0) {
Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
}
keySize = MinRSAKeySize;
}
}
Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
/*
Ruckus:
SEQUENCE:
OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)
RFC-7030:
SEQUENCE:
OID=1.2.840.113549.1.9.7 (challengePassword)
SEQUENCE:
OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
SET:
OID=1.3.132.0.34 (secp384r1)
SEQUENCE:
OID=1.2.840.113549.1.9.14 (extensionRequest)
SET:
OID=1.3.6.1.1.1.1.22 (mac-address)
OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)
1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
*/
// ECC Does not appear to be supported currently
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
if (curveName != null) {
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
} else {
kpg.initialize(keySize);
}
KeyPair kp = kpg.generateKeyPair();
X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
mClientKey = kp.getPrivate();
// !!! Map the idAttributes into an ASN1Set of values to pass to
// the PKCS10CertificationRequest - this code is using outdated BC classes and
// has *not* been tested.
ASN1Set attributes;
if (!idAttributes.isEmpty()) {
ASN1EncodableVector payload = new DEREncodableVector();
for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
ASN1Set values = new DERSet(entry.getValue());
Attribute attribute = new Attribute(type, values);
payload.add(attribute);
}
attributes = new DERSet(payload);
} else {
attributes = null;
}
return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}Example 66
| Project: SLAMD-master File: CreateEgg.java View source code |
/**
* Parses the command-line arguments and performs the appropriate processing.
*
* @param args The command-line arguments provided to this program.
*
* @throws Exception If a problem occurs while performing any processing.
*/
public static void main(String[] args) throws Exception {
String queryString = null;
String inputFile = null;
String outputFile = null;
boolean decrypt = false;
// Parse the command-line arguments provided to the program.
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-q")) {
queryString = args[++i];
} else if (args[i].equals("-i")) {
inputFile = args[++i];
} else if (args[i].equals("-o")) {
outputFile = args[++i];
} else if (args[i].equals("-d")) {
decrypt = true;
} else if (args[i].equals("-H")) {
displayUsage();
System.exit(0);
} else {
System.err.println("ERROR: Unrecognized argument\"" + args[i] + '"');
displayUsage();
System.exit(1);
}
}
// Validate the parameters provided.
if (queryString == null) {
System.err.println("ERROR: No query string provided (use -q)");
displayUsage();
System.exit(1);
}
if (inputFile == null) {
System.err.println("ERROR: No input file provided (use -i)");
displayUsage();
System.exit(1);
}
if (outputFile == null) {
if (decrypt) {
outputFile = inputFile + ".decrypted";
} else {
outputFile = inputFile + ".encrypted";
}
}
// command-line arguments.
if (decrypt) {
// Initialize the decryption mechanism.
AlgorithmParameters algorithmParams = AlgorithmParameters.getInstance(CIPHER_NAME);
algorithmParams.init(new PBEParameterSpec(SALT, ITERATIONS));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_NAME);
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(queryString.toCharArray()));
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, key, algorithmParams);
// Open the files and do the decryption.
int bytesIn;
int bytesOut;
int totalBytesRead = 0;
int totalBytesWritten = 0;
byte[] inBuffer = new byte[4096];
byte[] outBuffer = new byte[8192];
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
while ((bytesIn = inputStream.read(inBuffer)) > 0) {
bytesOut = cipher.update(inBuffer, 0, bytesIn, outBuffer);
outputStream.write(outBuffer, 0, bytesOut);
totalBytesRead += bytesIn;
totalBytesWritten += bytesOut;
}
outputStream.write(cipher.doFinal());
inputStream.close();
outputStream.flush();
outputStream.close();
System.out.println("Read " + totalBytesRead + " bytes from " + inputFile);
System.out.println("Wrote " + totalBytesWritten + " bytes to " + outputFile);
} else {
// Create an MD5 hash of the query string.
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
byte[] queryHashBytes = md5Digest.digest(queryString.getBytes("UTF-8"));
String queryHashStr = Base64.encode(queryHashBytes);
System.out.println("MD5 hash of query string is " + queryHashStr);
// Initialize the encryption mechanism.
AlgorithmParameters algorithmParams = AlgorithmParameters.getInstance(CIPHER_NAME);
algorithmParams.init(new PBEParameterSpec(SALT, ITERATIONS));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_NAME);
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(queryString.toCharArray()));
Cipher cipher = Cipher.getInstance(CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, key, algorithmParams);
// Open the files and do the encryption.
int bytesIn;
int bytesOut;
int totalBytesRead = 0;
int totalBytesWritten = 0;
byte[] inBuffer = new byte[4096];
byte[] outBuffer = new byte[8192];
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
while ((bytesIn = inputStream.read(inBuffer)) > 0) {
bytesOut = cipher.update(inBuffer, 0, bytesIn, outBuffer);
outputStream.write(outBuffer, 0, bytesOut);
totalBytesRead += bytesIn;
totalBytesWritten += bytesOut;
}
outputStream.write(cipher.doFinal());
inputStream.close();
outputStream.flush();
outputStream.close();
System.out.println("Read " + totalBytesRead + " bytes from " + inputFile);
System.out.println("Wrote " + totalBytesWritten + " bytes to " + outputFile);
}
}Example 67
| Project: strolch-master File: AesCryptoHelper.java View source code |
public static OutputStream wrapEncrypt(SecretKey secret, OutputStream outputStream) {
try {
// set up cipher
Cipher cipher = Cipher.getInstance(CIPHER);
cipher.init(Cipher.ENCRYPT_MODE, secret);
// set up the initialization vector
AlgorithmParameters params = cipher.getParameters();
byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
DBC.INTERIM.assertEquals("IV must be 16 bytes long!", 16, initVector.length);
// write the initialization vector, but not through the cipher output stream!
outputStream.write(initVector);
outputStream.flush();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
return cipherOutputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 68
| Project: Assignments-master File: PdfPublicKeySecurityHandler.java View source code |
private ASN1Primitive 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);
ASN1Primitive 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 ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
ASN1Set set = null;
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
return contentinfo.toASN1Primitive();
}Example 69
| Project: BitNomen-master File: OIDLookup.java View source code |
/** * Unfortunately, there's no easy way to do this. * Need to add a way to get parameters from each new key type. Makes it hard to add * new key types dynamically. The parameter interfaces should be cleaned up in Java. * So instead, we try reflection... **/ public static AlgorithmParameters getParametersFromKey(Key key) throws NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameters algParams = null; // Handle the obvious cases, try to get a little general with reflection. if (key instanceof RSAKey) { // do nothing, params should be null (as opposed to RSAKeyGenerator parameters, // which actually do contain stuff). Don't use those here. } if (key instanceof DSAKey) { DSAParams params = ((DSAKey) key).getParams(); algParams = AlgorithmParameters.getInstance("DSA"); // the only class implementing DSAParams is DSAParameterSpec algParams.init((AlgorithmParameterSpec) params); } else { // Let's see if we can find a method called getParams or getParameters that // returns something that can be coerced into an AlgorithmParameters or an AlgorithmParametersSpec. Method[] methods = key.getClass().getDeclaredMethods(); // Try them in order that we get them. for (int i = 0; i < methods.length; ++i) { if ((methods[i].getName().equalsIgnoreCase("getParams")) || (methods[i].getName().equalsIgnoreCase("getParameters"))) { if (AlgorithmParameters.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { algParams = (AlgorithmParameters) methods[i].invoke(key, args); if (null != algParams) { // we're done} break; } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } else if (AlgorithmParameterSpec.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { AlgorithmParameterSpec spec = (AlgorithmParameterSpec) methods[i].invoke(key, args); if (null == spec) { continue; } algParams = AlgorithmParameters.getInstance(key.getAlgorithm()); if (algParams != null) { algParams.init(spec); if (algParams != null) { break; } } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } } } } return algParams; }
Example 70
| Project: cdo-master File: DiffieHellman.java View source code |
public byte[] handleResponse(Client.Response response) {
try {
// Instantiate a DH public key from the client's encoded key material.
KeyFactory keyFactory = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(response.getClientPubKeyEnc());
PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
// Create and initialize DH KeyAgreement object
KeyAgreement keyAgree = KeyAgreement.getInstance("DH");
keyAgree.init(privateKey);
// Use Client's public key for the first (and only) phase of her version of the DH protocol.
keyAgree.doPhase(pubKey, true);
SecretKey sharedSecret = keyAgree.generateSecret(challenge.getSecretAlgorithm());
// Prepare the cipher used to decrypt
Cipher serverCipher = Cipher.getInstance(challenge.getCypherTransformation());
byte[] encodedParams = response.getParamsEnc();
if (encodedParams == null) {
serverCipher.init(Cipher.DECRYPT_MODE, sharedSecret);
} else {
// Instantiate AlgorithmParameters object from parameter encoding obtained from client
AlgorithmParameters params = AlgorithmParameters.getInstance(challenge.getSecretAlgorithm());
params.init(encodedParams);
serverCipher.init(Cipher.DECRYPT_MODE, sharedSecret, params);
}
// Decrypt
return serverCipher.doFinal(response.getCipherText());
} catch (GeneralSecurityException ex) {
throw new SecurityException(ex);
} catch (IOException ex) {
throw new IORuntimeException(ex);
}
}Example 71
| Project: eucalyptus-master File: JsonWebSignatureAlgorithm.java View source code |
public <K extends JsonWebKey> PublicKey publicKey(final K key) throws GeneralSecurityException {
final EcJsonWebKey webKey = key(key, EcJsonWebKey.class);
if (!name().equals(webKey.getAlg())) {
throw new GeneralSecurityException("Invalid key algorithm " + webKey.getAlg() + " for " + name());
}
if (!expectedCurve.equals(webKey.getCrv())) {
throw new GeneralSecurityException("Invalid curve " + webKey.getCrv() + " for " + name());
}
final BigInteger x = new BigInteger(1, BaseEncoding.base64Url().decode(webKey.getX()));
final BigInteger y = new BigInteger(1, BaseEncoding.base64Url().decode(webKey.getY()));
final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec(jcaCurve));
final ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
return KeyFactory.getInstance("EC").generatePublic(new ECPublicKeySpec(new ECPoint(x, y), ecParameters));
}Example 72
| Project: irssiconnectbot-master File: PubkeyUtils.java View source code |
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}Example 73
| Project: iText-4.2.0-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 74
| Project: itextpdf-master File: PdfPublicKeySecurityHandler.java View source code |
private ASN1Primitive 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);
ASN1Primitive 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 ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
ASN1Set set = null;
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
return contentinfo.toASN1Primitive();
}Example 75
| Project: junrar-android-master File: X509CertificateImpl.java View source code |
/**
* Parse a DER stream into an X.509 certificate.
*
* @param encoded The encoded bytes.
*/
private void parse(InputStream encoded) throws Exception {
DERReader der = new DERReader(encoded);
// Certificate ::= SEQUENCE {
DERValue cert = der.read();
debug("start Certificate len == " + cert.getLength());
this.encoded = cert.getEncoded();
if (!cert.isConstructed()) {
throw new IOException("malformed Certificate");
}
// TBSCertificate ::= SEQUENCE {
DERValue tbsCert = der.read();
if (tbsCert.getValue() != DER.CONSTRUCTED_VALUE) {
throw new IOException("malformed TBSCertificate");
}
tbsCertBytes = tbsCert.getEncoded();
debug("start TBSCertificate len == " + tbsCert.getLength());
// Version ::= INTEGER [0] { v1(0), v2(1), v3(2) }
DERValue val = der.read();
if (val.getTagClass() == DER.CONTEXT && val.getTag() == 0) {
version = ((BigInteger) der.read().getValue()).intValue() + 1;
val = der.read();
} else {
version = 1;
}
debug("read version == " + version);
// SerialNumber ::= INTEGER
serialNo = (BigInteger) val.getValue();
debug("read serial number == " + serialNo);
// AlgorithmIdentifier ::= SEQUENCE {
val = der.read();
if (!val.isConstructed()) {
throw new IOException("malformed AlgorithmIdentifier");
}
int certAlgLen = val.getLength();
debug("start AlgorithmIdentifier len == " + certAlgLen);
val = der.read();
// algorithm OBJECT IDENTIFIER,
algId = (OID) val.getValue();
debug("read algorithm ID == " + algId);
// parameters ANY DEFINED BY algorithm OPTIONAL }
if (certAlgLen > val.getEncodedLength()) {
val = der.read();
if (val == null) {
algVal = null;
} else {
algVal = val.getEncoded();
}
if (val.isConstructed()) {
encoded.skip(val.getLength());
}
debug("read algorithm parameters == " + algVal);
}
// issuer Name,
val = der.read();
issuer = new X500Name(val.getEncoded());
der.skip(val.getLength());
debug("read issuer == " + issuer);
// notAfter Time }
if (!der.read().isConstructed()) {
throw new IOException("malformed Validity");
}
notBefore = (Date) der.read().getValue();
notAfter = (Date) der.read().getValue();
debug("read notBefore == " + notBefore);
debug("read notAfter == " + notAfter);
// subject Name,
val = der.read();
subject = new X500Name(val.getEncoded());
der.skip(val.getLength());
debug("read subject == " + subject);
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DERValue spki = der.read();
if (!spki.isConstructed()) {
throw new IOException("malformed SubjectPublicKeyInfo");
}
KeyFactory spkFac = KeyFactory.getInstance("X.509");
subjectKey = spkFac.generatePublic(new X509EncodedKeySpec(spki.getEncoded()));
der.skip(spki.getLength());
debug("read subjectPublicKey == " + subjectKey);
if (version > 1) {
val = der.read();
}
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 1) {
byte[] b = (byte[]) val.getValue();
issuerUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
debug("read issuerUniqueId == " + issuerUniqueId);
val = der.read();
}
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 2) {
byte[] b = (byte[]) val.getValue();
subjectUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
debug("read subjectUniqueId == " + subjectUniqueId);
val = der.read();
}
if (version >= 3 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 3) {
val = der.read();
debug("start Extensions len == " + val.getLength());
int len = 0;
while (len < val.getLength()) {
DERValue ext = der.read();
debug("start extension len == " + ext.getLength());
Extension e = new Extension(ext.getEncoded());
extensions.put(e.getOid(), e);
der.skip(ext.getLength());
len += ext.getEncodedLength();
debug("count == " + len);
}
}
val = der.read();
if (!val.isConstructed()) {
throw new IOException("malformed AlgorithmIdentifier");
}
int sigAlgLen = val.getLength();
debug("start AlgorithmIdentifier len == " + sigAlgLen);
val = der.read();
sigAlgId = (OID) val.getValue();
debug("read algorithm id == " + sigAlgId);
if (sigAlgLen > val.getEncodedLength()) {
val = der.read();
if (val.getValue() == null) {
if (subjectKey instanceof DSAPublicKey) {
AlgorithmParameters params = AlgorithmParameters.getInstance("DSA");
DSAParams dsap = ((DSAPublicKey) subjectKey).getParams();
DSAParameterSpec spec = new DSAParameterSpec(dsap.getP(), dsap.getQ(), dsap.getG());
params.init(spec);
sigAlgVal = params.getEncoded();
}
} else {
sigAlgVal = (byte[]) val.getEncoded();
}
if (val.isConstructed()) {
encoded.skip(val.getLength());
}
debug("read parameters == " + sigAlgVal);
}
signature = ((BitString) der.read().getValue()).toByteArray();
debug("read signature ==\n" + Util.hexDump(signature, ">>>> "));
}Example 76
| Project: PDF-to-unusual-HTML-master File: PublicKeySecurityHandler.java View source code |
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();
}Example 77
| Project: PDFAInspector-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 78
| Project: ssl_npn-master File: SSLAlgorithmConstraints.java View source code |
public boolean permits(Set<CryptoPrimitive> primitives, String algorithm, AlgorithmParameters parameters) {
boolean permitted = true;
if (peerAlgConstraints != null) {
permitted = peerAlgConstraints.permits(primitives, algorithm, parameters);
}
if (permitted && userAlgConstraints != null) {
permitted = userAlgConstraints.permits(primitives, algorithm, parameters);
}
if (permitted) {
permitted = tlsDisabledAlgConstraints.permits(primitives, algorithm, parameters);
}
if (permitted && enabledX509DisabledAlgConstraints) {
permitted = x509DisabledAlgConstraints.permits(primitives, algorithm, parameters);
}
return permitted;
}Example 79
| Project: sysart-itext-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 80
| Project: UNH_NDN-master File: StaticContentKeys.java View source code |
/**
* Generate a segment encryption or decryption cipher using this stored
* key material to encrypt or decrypt a particular segment.
*
* This will use the CCN defaults for IV handling, to ensure that segments
* of a given larger piece of content do not have overlapping key streams.
* Higher-level functionality embodied in the library (or application-specific
* code) should be used to make sure that the key, _masterIV pair used for a
* given multi-block piece of content is unique for that content.
*
* CCN encryption algorithms assume deterministic IV generation (e.g. from
* cryptographic MAC or ciphers themselves), and therefore do not transport
* the IV explicitly. Applications that wish to do so need to arrange
* IV transport.
*
* We assume this stream starts on the first block of a multi-block segement,
* so for CTR mode, the initial block counter is 1 (block == encryption
* block). (Conventions for counter start them at 1, not 0.) The cipher
* will automatically increment the counter; if it overflows the two bytes
* we've given to it it will start to increment into the segment number.
* This runs the risk of potentially using up some of the IV space of
* other segments.
*
* CTR_init = IV_master || segment_number || block_counter
* CBC_iv = E_Ko(IV_master || segment_number || 0x0001)
* (just to make it easier, use the same feed value)
*
* CTR value is 16 bytes.
* 8 bytes are the IV.
* 6 bytes are the segment number.
* last 2 bytes are the block number (for 16 byte blocks); if you
* have more space, use it for the block counter.
* IV value is the block width of the cipher.
*
* @param segmentNumber segment to encrypt/decrypt
* @param encryption true for encryption, false for decryption
* @return the Cipher
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws ContentEncodingException
* @see getSegmentEncryptionCipher(long)
*/
protected Cipher getSegmentCipher(ContentName contentName, PublisherPublicKeyDigest publisher, long segmentNumber, boolean encryption) throws InvalidKeyException, InvalidAlgorithmParameterException, ContentEncodingException {
Cipher cipher = getCipher();
// Construct the IV/initial counter.
if (0 == cipher.getBlockSize()) {
Log.warning(_encryptionAlgorithm + " is not a block cipher!");
throw new InvalidAlgorithmParameterException(_encryptionAlgorithm + " is not a block cipher!");
}
KeyAndIV keyAndIV = getKeyAndIVForContent(contentName, publisher, segmentNumber);
if (keyAndIV.getIV().length < IV_MASTER_LENGTH) {
throw new InvalidAlgorithmParameterException("Master IV length must be at least " + IV_MASTER_LENGTH + " bytes, it is: " + _masterKeyAndIVCtr.getIV().length);
}
IvParameterSpec iv_ctrSpec = buildIVCtr(keyAndIV, segmentNumber, cipher.getBlockSize());
AlgorithmParameters algorithmParams = null;
try {
algorithmParams = AlgorithmParameters.getInstance(getBaseAlgorithm());
algorithmParams.init(iv_ctrSpec);
} catch (NoSuchAlgorithmException e) {
Log.warning("Unexpected exception: have already validated that algorithm {0} exists: {1}", cipher.getAlgorithm(), e);
throw new InvalidKeyException("Unexpected exception: have already validated that algorithm " + cipher.getAlgorithm() + " exists: " + e);
} catch (InvalidParameterSpecException e) {
Log.warning("InvalidParameterSpecException attempting to create algorithm parameters: {0}", e);
throw new InvalidAlgorithmParameterException("Error creating a parameter object from IV/CTR spec!", e);
}
Log.finest(encryption ? "En" : "De" + "cryption Key: " + DataUtils.printHexBytes(keyAndIV.getKey().getEncoded()) + " iv=" + DataUtils.printHexBytes(iv_ctrSpec.getIV()));
cipher.init(encryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keyAndIV.getKey(), algorithmParams);
return cipher;
}Example 81
| Project: wgen-iText-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 82
| Project: xipki-master File: P11RSAPSSSignatureSpi.java View source code |
@Override protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = AlgorithmParameters.getInstance("PSS", "BC"); engineParams.init(paramSpec); } catch (Exception ex) { throw new RuntimeException(ex.getMessage(), ex); } } } return engineParams; }
Example 83
| Project: alien-ofelia-conet-ccnx-master File: OIDLookup.java View source code |
/** * Unfortunately, there's no easy way to do this. * Need to add a way to get parameters from each new key type. Makes it hard to add * new key types dynamically. The parameter interfaces should be cleaned up in Java. * So instead, we try reflection... **/ public static AlgorithmParameters getParametersFromKey(Key key) throws NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameters algParams = null; // Handle the obvious cases, try to get a little general with reflection. if (key instanceof RSAKey) { // do nothing, params should be null (as opposed to RSAKeyGenerator parameters, // which actually do contain stuff). Don't use those here. } if (key instanceof DSAKey) { DSAParams params = ((DSAKey) key).getParams(); algParams = AlgorithmParameters.getInstance("DSA"); // the only class implementing DSAParams is DSAParameterSpec algParams.init((AlgorithmParameterSpec) params); } else { // Let's see if we can find a method called getParams or getParameters that // returns something that can be coerced into an AlgorithmParameters or an AlgorithmParametersSpec. Method[] methods = key.getClass().getDeclaredMethods(); // Try them in order that we get them. for (int i = 0; i < methods.length; ++i) { if ((methods[i].getName().equalsIgnoreCase("getParams")) || (methods[i].getName().equalsIgnoreCase("getParameters"))) { if (AlgorithmParameters.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { algParams = (AlgorithmParameters) methods[i].invoke(key, args); if (null != algParams) { // we're done} break; } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } else if (AlgorithmParameterSpec.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { AlgorithmParameterSpec spec = (AlgorithmParameterSpec) methods[i].invoke(key, args); if (null == spec) { continue; } algParams = AlgorithmParameters.getInstance(key.getAlgorithm()); if (algParams != null) { algParams.init(spec); if (algParams != null) { break; } } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } } } } return algParams; }
Example 84
| Project: appengine-export-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 85
| Project: BSSH-master File: PubkeyUtils.java View source code |
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}Example 86
| Project: ccnx-master File: OIDLookup.java View source code |
/** * Unfortunately, there's no easy way to do this. * Need to add a way to get parameters from each new key type. Makes it hard to add * new key types dynamically. The parameter interfaces should be cleaned up in Java. * So instead, we try reflection... **/ public static AlgorithmParameters getParametersFromKey(Key key) throws NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameters algParams = null; // Handle the obvious cases, try to get a little general with reflection. if (key instanceof RSAKey) { // do nothing, params should be null (as opposed to RSAKeyGenerator parameters, // which actually do contain stuff). Don't use those here. } if (key instanceof DSAKey) { DSAParams params = ((DSAKey) key).getParams(); algParams = AlgorithmParameters.getInstance("DSA"); // the only class implementing DSAParams is DSAParameterSpec algParams.init((AlgorithmParameterSpec) params); } else { // Let's see if we can find a method called getParams or getParameters that // returns something that can be coerced into an AlgorithmParameters or an AlgorithmParametersSpec. Method[] methods = key.getClass().getDeclaredMethods(); // Try them in order that we get them. for (int i = 0; i < methods.length; ++i) { if ((methods[i].getName().equalsIgnoreCase("getParams")) || (methods[i].getName().equalsIgnoreCase("getParameters"))) { if (AlgorithmParameters.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { algParams = (AlgorithmParameters) methods[i].invoke(key, args); if (null != algParams) { // we're done} break; } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } else if (AlgorithmParameterSpec.class.isAssignableFrom(methods[i].getReturnType())) { // Pass in null for any arguments. Object[] args = new Object[methods[i].getParameterTypes().length]; try { AlgorithmParameterSpec spec = (AlgorithmParameterSpec) methods[i].invoke(key, args); if (null == spec) { continue; } algParams = AlgorithmParameters.getInstance(key.getAlgorithm()); if (algParams != null) { algParams.init(spec); if (algParams != null) { break; } } } catch (Exception ex) { if (debug) { System.out.println("Tried invoking method: " + methods[i].getName() + " on object of type: " + key.getClass().getName() + ", got exception: " + ex.getClass().getName() + " message: " + ex.getMessage()); } continue; } } } } } return algParams; }
Example 87
| Project: connectbot-master File: PubkeyUtils.java View source code |
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}Example 88
| Project: i2p.i2p-master File: ECConstants.java View source code |
/**
* Generate a spec from a curve name
* @return null if fail
*/
private static ECParameterSpec genSpec(String name) {
// is not a ECParameterSpec.
try {
AlgorithmParameters ap;
try {
ap = AlgorithmParameters.getInstance("EC");
} catch (GeneralSecurityException e) {
if (BC_AVAILABLE) {
log("Named curve " + name + " is not available, trying BC", e);
ap = AlgorithmParameters.getInstance("EC", "BC");
log("Fallback to BC worked for named curve " + name);
} else {
throw e;
}
}
ECGenParameterSpec ecgps = new ECGenParameterSpec(name);
ap.init(ecgps);
ECParameterSpec rv = ap.getParameterSpec(ECParameterSpec.class);
log("Named curve " + name + " loaded");
return rv;
} catch (GeneralSecurityException e) {
log("Named curve " + name + " is not available", e);
return null;
}
}Example 89
| Project: itext-as-in-free-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 90
| Project: itext-forked-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 91
| Project: itext2-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 92
| Project: pades_signing_2.1.5-master File: PdfPublicKeySecurityHandler.java View source code |
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();
}Example 93
| Project: PdfBox-Android-master File: PublicKeySecurityHandler.java View source code |
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException {
String algorithm = "1.2.840.113549.3.2";
AlgorithmParameterGenerator apg;
KeyGenerator keygen;
Cipher cipher;
try {
apg = AlgorithmParameterGenerator.getInstance(algorithm);
keygen = KeyGenerator.getInstance(algorithm, "SC");
cipher = Cipher.getInstance(algorithm, "SC");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
}
AlgorithmParameters parameters = apg.generateParameters();
ASN1InputStream input = new ASN1InputStream(parameters.getEncoded("ASN.1"));
ASN1Primitive object = input.readObject();
input.close();
keygen.init(128);
SecretKey secretkey = keygen.generateKey();
cipher.init(1, secretkey, parameters);
byte[] bytes = cipher.doFinal(in);
KeyTransRecipientInfo recipientInfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet set = new DERSet(new RecipientInfo(recipientInfo));
AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(algorithm), object);
EncryptedContentInfo encryptedInfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmId, new DEROctetString(bytes));
EnvelopedData enveloped = new EnvelopedData(null, set, encryptedInfo, (ASN1Set) null);
ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, enveloped);
return contentInfo.toASN1Primitive();
}Example 94
| Project: pdfbox-master File: PublicKeySecurityHandler.java View source code |
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException {
String algorithm = "1.2.840.113549.3.2";
AlgorithmParameterGenerator apg;
KeyGenerator keygen;
Cipher cipher;
try {
apg = AlgorithmParameterGenerator.getInstance(algorithm, SecurityProvider.getProvider());
keygen = KeyGenerator.getInstance(algorithm, SecurityProvider.getProvider());
cipher = Cipher.getInstance(algorithm, SecurityProvider.getProvider());
} catch (NoSuchAlgorithmException e) {
throw new IOException("Could not find a suitable javax.crypto provider for algorithm " + algorithm + "; possible reason: using an unsigned .jar file", e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException("Could not find a suitable javax.crypto provider", e);
}
AlgorithmParameters parameters = apg.generateParameters();
ASN1Primitive object;
try (ASN1InputStream input = new ASN1InputStream(parameters.getEncoded("ASN.1"))) {
object = input.readObject();
}
keygen.init(128);
SecretKey secretkey = keygen.generateKey();
cipher.init(1, secretkey, parameters);
byte[] bytes = cipher.doFinal(in);
KeyTransRecipientInfo recipientInfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet set = new DERSet(new RecipientInfo(recipientInfo));
AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(algorithm), object);
EncryptedContentInfo encryptedInfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmId, new DEROctetString(bytes));
EnvelopedData enveloped = new EnvelopedData(null, set, encryptedInfo, (ASN1Set) null);
ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, enveloped);
return contentInfo.toASN1Primitive();
}Example 95
| Project: remote-desktop-clients-master File: PubkeyUtils.java View source code |
/*
* OpenSSH compatibility methods
*/
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}Example 96
| Project: JCGO-master File: X509Certificate.java View source code |
/**
* Parse a DER stream into an X.509 certificate.
*
* @param encoded The encoded bytes.
*/
private void parse(InputStream encoded) throws Exception {
DERReader der = new DERReader(encoded);
// Certificate ::= SEQUENCE {
DERValue cert = der.read();
Logger logger = logger();
logger.log(Component.X509, "start Certificate len == {0}", Integer.valueOf(cert.getLength()));
this.encoded = cert.getEncoded();
if (!cert.isConstructed()) {
throw new IOException("malformed Certificate");
}
// TBSCertificate ::= SEQUENCE {
DERValue tbsCert = der.read();
if (tbsCert.getValue() != DER.CONSTRUCTED_VALUE) {
throw new IOException("malformed TBSCertificate");
}
tbsCertBytes = tbsCert.getEncoded();
logger.log(Component.X509, "start TBSCertificate len == {0}", Integer.valueOf(tbsCert.getLength()));
// Version ::= INTEGER [0] { v1(0), v2(1), v3(2) }
DERValue val = der.read();
if (val.getTagClass() == DER.CONTEXT && val.getTag() == 0) {
version = ((BigInteger) der.read().getValue()).intValue() + 1;
val = der.read();
} else {
version = 1;
}
logger.log(Component.X509, "read version == {0}", Integer.valueOf(version));
// SerialNumber ::= INTEGER
serialNo = (BigInteger) val.getValue();
logger.log(Component.X509, "read serial number == {0}", serialNo);
// AlgorithmIdentifier ::= SEQUENCE {
val = der.read();
if (!val.isConstructed()) {
throw new IOException("malformed AlgorithmIdentifier");
}
int certAlgLen = val.getLength();
logger.log(Component.X509, "start AlgorithmIdentifier len == {0}", Integer.valueOf(certAlgLen));
val = der.read();
// algorithm OBJECT IDENTIFIER,
algId = (OID) val.getValue();
logger.log(Component.X509, "read algorithm ID == {0}", algId);
// parameters ANY DEFINED BY algorithm OPTIONAL }
if (certAlgLen > val.getEncodedLength()) {
val = der.read();
if (val == null) {
algVal = null;
} else {
algVal = val.getEncoded();
if (val.isConstructed())
encoded.skip(val.getLength());
}
logger.log(Component.X509, "read algorithm parameters == {0}", algVal);
}
// issuer Name,
val = der.read();
issuer = new X500DistinguishedName(val.getEncoded());
der.skip(val.getLength());
logger.log(Component.X509, "read issuer == {0}", issuer);
// notAfter Time }
if (!der.read().isConstructed()) {
throw new IOException("malformed Validity");
}
notBefore = (Date) der.read().getValue();
logger.log(Component.X509, "read notBefore == {0}", notBefore);
notAfter = (Date) der.read().getValue();
logger.log(Component.X509, "read notAfter == {0}", notAfter);
// subject Name,
val = der.read();
subject = new X500DistinguishedName(val.getEncoded());
der.skip(val.getLength());
logger.log(Component.X509, "read subject == {0}", subject);
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
DERValue spki = der.read();
if (!spki.isConstructed()) {
throw new IOException("malformed SubjectPublicKeyInfo");
}
KeyFactory spkFac = KeyFactory.getInstance("X.509");
subjectKey = spkFac.generatePublic(new X509EncodedKeySpec(spki.getEncoded()));
der.skip(spki.getLength());
logger.log(Component.X509, "read subjectPublicKey == {0}", subjectKey);
val = der.read();
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 1) {
byte[] b = (byte[]) val.getValue();
issuerUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
logger.log(Component.X509, "read issuerUniqueId == {0}", issuerUniqueId);
val = der.read();
}
if (version >= 2 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 2) {
byte[] b = (byte[]) val.getValue();
subjectUniqueId = new BitString(b, 1, b.length - 1, b[0] & 0xFF);
logger.log(Component.X509, "read subjectUniqueId == {0}", subjectUniqueId);
val = der.read();
}
if (version >= 3 && val.getTagClass() != DER.UNIVERSAL && val.getTag() == 3) {
val = der.read();
logger.log(Component.X509, "start Extensions len == {0}", Integer.valueOf(val.getLength()));
int len = 0;
while (len < val.getLength()) {
DERValue ext = der.read();
logger.log(Component.X509, "start extension len == {0}", Integer.valueOf(ext.getLength()));
Extension e = new Extension(ext.getEncoded());
extensions.put(e.getOid(), e);
der.skip(ext.getLength());
len += ext.getEncodedLength();
logger.log(Component.X509, "read extension {0} == {1}", new Object[] { e.getOid(), e });
logger.log(Component.X509, "count == {0}", Integer.valueOf(len));
}
val = der.read();
}
logger.log(Component.X509, "read value {0}", val);
if (!val.isConstructed()) {
throw new CertificateException("malformed AlgorithmIdentifier");
}
int sigAlgLen = val.getLength();
logger.log(Component.X509, "start AlgorithmIdentifier len == {0}", Integer.valueOf(sigAlgLen));
val = der.read();
sigAlgId = (OID) val.getValue();
logger.log(Component.X509, "read algorithm id == {0}", sigAlgId);
if (sigAlgLen > val.getEncodedLength()) {
val = der.read();
if (val.getValue() == null) {
if (subjectKey instanceof DSAPublicKey) {
AlgorithmParameters params = AlgorithmParameters.getInstance("DSA");
DSAParams dsap = ((DSAPublicKey) subjectKey).getParams();
DSAParameterSpec spec = new DSAParameterSpec(dsap.getP(), dsap.getQ(), dsap.getG());
params.init(spec);
sigAlgVal = params.getEncoded();
}
} else {
sigAlgVal = (byte[]) val.getEncoded();
}
if (val.isConstructed()) {
encoded.skip(val.getLength());
}
logger.log(Component.X509, "read parameters == {0}", sigAlgVal);
}
signature = ((BitString) der.read().getValue()).toByteArray();
logger.log(Component.X509, "read signature ==\n{0}", Util.hexDump(signature, ">>>> "));
}Example 97
| Project: jgit-master File: WalkEncryption.java View source code |
@Override
OutputStream encrypt(OutputStream output) throws IOException {
try {
Cipher cipher = InsecureCipherFactory.create(cipherAlgo);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
AlgorithmParameters params = cipher.getParameters();
if (params == null) {
context = EMPTY;
} else {
context = Base64.encodeBytes(params.getEncoded());
}
return new CipherOutputStream(output, cipher);
} catch (Exception e) {
throw error(e);
}
}Example 98
| Project: ranger-master File: RangerKeyStore.java View source code |
private Key unsealKey(SealedObject sealedKey, char[] password) throws Exception {
// Create SecretKey
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
pbeKeySpec.clearPassword();
// Get the AlgorithmParameters from RangerSealedObject
AlgorithmParameters algorithmParameters = null;
if (sealedKey instanceof RangerSealedObject) {
algorithmParameters = ((RangerSealedObject) sealedKey).getParameters();
} else {
algorithmParameters = new RangerSealedObject(sealedKey).getParameters();
}
// Unseal the Key
Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
cipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameters);
return (Key) sealedKey.getObject(cipher);
}Example 99
| Project: sling-master File: TopologyRequestValidator.java View source code |
/**
* Encrypt a payload with the numbed key/
*
* @param payload the payload.
* @param keyNo the key number.
* @return an encrypted version.
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeySpecException
* @throws InvalidParameterSpecException
*/
private List<String> encrypt(String payload) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidParameterSpecException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] salt = new byte[9];
random.nextBytes(salt);
cipher.init(Cipher.ENCRYPT_MODE, getCiperKey(salt));
AlgorithmParameters params = cipher.getParameters();
List<String> encrypted = new ArrayList<String>();
encrypted.add(new String(Base64.encodeBase64(salt)));
encrypted.add(new String(Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV())));
encrypted.add(new String(Base64.encodeBase64(cipher.doFinal(payload.getBytes("UTF-8")))));
return encrypted;
}Example 100
| Project: wycheproof-master File: AesGcmTest.java View source code |
/**
* The default authentication tag size should be 128-bit by default for the following reasons:
* <br>
* (1) Security: Ferguson, N., Authentication Weaknesses in GCM, Natl. Inst. Stand. Technol. [Web
* page], http://www.csrc.nist.gov/groups/ST/toolkit/BCM/documents/comments/
* CWC-GCM/Ferguson2.pdf, May 20, 2005. This paper points out that a n-bit tag has lower strength
* than expected. <br>
* (2) Compatibility: Assume an implementer tests some code using one provider than switches to
* another provider. Such a switch should ideally not lower the security. <br>
* BouncyCastle used to have only 12-byte authentication tag (b/26186727).
*/
public void testDefaultTagSizeAlgorithmParameterGenerator() throws Exception {
byte[] input = new byte[10];
byte[] key = new byte[16];
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
try {
AlgorithmParameterGenerator.getInstance("GCM");
} catch (NoSuchAlgorithmException ex) {
System.out.println("testDefaultTagSizeAlgorithmParameterGenerator:" + ex.toString());
return;
}
AlgorithmParameters param = AlgorithmParameterGenerator.getInstance("GCM").generateParameters();
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), param);
byte[] output = cipher.doFinal(input);
assertEquals(input.length + 16, output.length);
}Example 101
| Project: jxse-master File: PSEUtils.java View source code |
/**
* Given a private key and a password, encrypt the private key using the
* PBESE1 algorithm.
*
* @param password The password which will be used.
* @param privkey The private key to be encrypted.
* @param iterations Number of iterations.
* @return An encrypted private key info or null if the key could not be
* encrypted.
*/
public static EncryptedPrivateKeyInfo pkcs5_Encrypt_pbePrivateKey(char[] password, PrivateKey privkey, int iterations) {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
byte[] salt = new byte[8];
UTILS.srng.nextBytes(salt);
try {
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, iterations);
// convert password into a SecretKey object, using a PBE key factory.
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PKCS5_PBSE1_ALGO);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance(PKCS5_PBSE1_ALGO);
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
byte[] encryptedPrivKey = pbeCipher.doFinal(privkey.getEncoded());
AlgorithmParameters algo = AlgorithmParameters.getInstance(PKCS5_PBSE1_ALGO);
algo.init(pbeParamSpec);
EncryptedPrivateKeyInfo result = new EncryptedPrivateKeyInfo(algo, encryptedPrivKey);
return result;
} catch (Exception failed) {
Logging.logCheckedWarning(LOG, "Encrypt failed\n", failed);
return null;
}
}