use of sun.security.x509.AlgorithmId in project OpenAM by OpenRock.
the class JwtGenerator method main.
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Usage: JwtGenerator <subject> <issuer> <audience>");
System.exit(1);
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
KeyPair keyPair = keyGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
long validTime = System.currentTimeMillis() + 1000 * 60 * 60 * 24 / 2;
String jwt = new JwtBuilderFactory().jws(new SigningManager().newRsaSigningHandler(keyPair.getPrivate())).headers().alg(JwsAlgorithm.RS256).done().claims(new JwtClaimsSet(json(object(field("iss", args[0]), field("sub", args[1]), field("aud", args[2]), field("exp", validTime / 1000))).asMap())).build();
System.out.println("JWT: " + jwt);
Calendar expiry = Calendar.getInstance();
expiry.add(Calendar.DAY_OF_YEAR, 7);
X509CertInfo info = new X509CertInfo();
CertificateValidity interval = new CertificateValidity(new Date(), new Date(validTime));
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name("CN=ForgeRock,L=Bristol,C=GB");
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(keyPair.getPrivate(), "SHA256withRSA");
System.out.println("Certificate:");
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(X509Factory.BEGIN_CERT);
encoder.encodeBuffer(cert.getEncoded(), System.out);
System.out.println(X509Factory.END_CERT);
}
use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.
the class PKCS7 method generateSignedData.
/**
* Assembles a PKCS #7 signed data message that optionally includes a
* signature timestamp.
*
* @param signature the signature bytes
* @param signerChain the signer's X.509 certificate chain
* @param content the content that is signed; specify null to not include
* it in the PKCS7 data
* @param signatureAlgorithm the name of the signature algorithm
* @param tsaURI the URI of the Timestamping Authority; or null if no
* timestamp is requested
* @param tSAPolicyID the TSAPolicyID of the Timestamping Authority as a
* numerical object identifier; or null if we leave the TSA server
* to choose one. This argument is only used when tsaURI is provided
* @return the bytes of the encoded PKCS #7 signed data message
* @throws NoSuchAlgorithmException The exception is thrown if the signature
* algorithm is unrecognised.
* @throws CertificateException The exception is thrown if an error occurs
* while processing the signer's certificate or the TSA's
* certificate.
* @throws IOException The exception is thrown if an error occurs while
* generating the signature timestamp or while generating the signed
* data message.
*/
public static byte[] generateSignedData(byte[] signature, X509Certificate[] signerChain, byte[] content, String signatureAlgorithm, URI tsaURI, String tSAPolicyID, String tSADigestAlg) throws CertificateException, IOException, NoSuchAlgorithmException {
// Generate the timestamp token
PKCS9Attributes unauthAttrs = null;
if (tsaURI != null) {
// Timestamp the signature
HttpTimestamper tsa = new HttpTimestamper(tsaURI);
byte[] tsToken = generateTimestampToken(tsa, tSAPolicyID, tSADigestAlg, signature);
// Insert the timestamp token into the PKCS #7 signer info element
// (as an unsigned attribute)
unauthAttrs = new PKCS9Attributes(new PKCS9Attribute[] { new PKCS9Attribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_STR, tsToken) });
}
// Create the SignerInfo
X500Name issuerName = X500Name.asX500Name(signerChain[0].getIssuerX500Principal());
BigInteger serialNumber = signerChain[0].getSerialNumber();
String encAlg = AlgorithmId.getEncAlgFromSigAlg(signatureAlgorithm);
String digAlg = AlgorithmId.getDigAlgFromSigAlg(signatureAlgorithm);
SignerInfo signerInfo = new SignerInfo(issuerName, serialNumber, AlgorithmId.get(digAlg), null, AlgorithmId.get(encAlg), signature, unauthAttrs);
// Create the PKCS #7 signed data message
SignerInfo[] signerInfos = { signerInfo };
AlgorithmId[] algorithms = { signerInfo.getDigestAlgorithmId() };
// Include or exclude content
ContentInfo contentInfo = (content == null) ? new ContentInfo(ContentInfo.DATA_OID, null) : new ContentInfo(content);
PKCS7 pkcs7 = new PKCS7(algorithms, contentInfo, signerChain, signerInfos);
ByteArrayOutputStream p7out = new ByteArrayOutputStream();
pkcs7.encodeSignedData(p7out);
return p7out.toByteArray();
}
use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method encryptPrivateKey.
/*
* Encrypt private key using Password-based encryption (PBE)
* as defined in PKCS#5.
*
* NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
* used to derive the key and IV.
*
* @return encrypted private key encoded as EncryptedPrivateKeyInfo
*/
private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
byte[] key = null;
try {
String algorithm;
AlgorithmParameters algParams;
AlgorithmId algid;
// Initialize PBE algorithm and parameters
algorithm = passwordProtection.getProtectionAlgorithm();
if (algorithm != null) {
AlgorithmParameterSpec algParamSpec = passwordProtection.getProtectionParameters();
if (algParamSpec != null) {
algParams = AlgorithmParameters.getInstance(algorithm);
algParams.init(algParamSpec);
} else {
algParams = getAlgorithmParameters(algorithm);
}
} else {
// Check default key protection algorithm for PKCS12 keystores
algorithm = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
String prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[0]);
if (prop == null) {
prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[1]);
}
return prop;
}
});
if (algorithm == null || algorithm.isEmpty()) {
algorithm = "PBEWithSHA1AndDESede";
}
algParams = getAlgorithmParameters(algorithm);
}
ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
if (pbeOID == null) {
throw new IOException("PBE algorithm '" + algorithm + " 'is not supported for key entry protection");
}
// Use JCE
SecretKey skey = getPBEKey(passwordProtection.getPassword());
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
byte[] encryptedKey = cipher.doFinal(data);
algid = new AlgorithmId(pbeOID, cipher.getParameters());
if (debug != null) {
debug.println(" (Cipher algorithm: " + cipher.getAlgorithm() + ")");
}
// wrap encrypted private key in EncryptedPrivateKeyInfo
// as defined in PKCS#8
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
key = encrInfo.getEncoded();
} catch (Exception e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
uke.initCause(e);
throw uke;
}
return key;
}
use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.
the class KeyProtector method protect.
/*
* Protects the given plaintext key, using the password provided at
* construction time.
*/
public byte[] protect(Key key) throws KeyStoreException {
int i;
int numRounds;
byte[] digest;
// offset in xorKey where next digest will be stored
int xorOffset;
int encrKeyOffset = 0;
if (key == null) {
throw new IllegalArgumentException("plaintext key can't be null");
}
if (!"PKCS#8".equalsIgnoreCase(key.getFormat())) {
throw new KeyStoreException("Cannot get key bytes, not PKCS#8 encoded");
}
byte[] plainKey = key.getEncoded();
if (plainKey == null) {
throw new KeyStoreException("Cannot get key bytes, encoding not supported");
}
// Determine the number of digest rounds
numRounds = plainKey.length / DIGEST_LEN;
if ((plainKey.length % DIGEST_LEN) != 0)
numRounds++;
// Create a random salt
byte[] salt = new byte[SALT_LEN];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
// Set up the byte array which will be XORed with "plainKey"
byte[] xorKey = new byte[plainKey.length];
// Compute the digests, and store them in "xorKey"
for (i = 0, xorOffset = 0, digest = salt; i < numRounds; i++, xorOffset += DIGEST_LEN) {
md.update(passwdBytes);
md.update(digest);
digest = md.digest();
md.reset();
// Copy the digest into "xorKey"
if (i < numRounds - 1) {
System.arraycopy(digest, 0, xorKey, xorOffset, digest.length);
} else {
System.arraycopy(digest, 0, xorKey, xorOffset, xorKey.length - xorOffset);
}
}
// XOR "plainKey" with "xorKey", and store the result in "tmpKey"
byte[] tmpKey = new byte[plainKey.length];
for (i = 0; i < tmpKey.length; i++) {
tmpKey[i] = (byte) (plainKey[i] ^ xorKey[i]);
}
// Store salt and "tmpKey" in "encrKey"
byte[] encrKey = new byte[salt.length + tmpKey.length + DIGEST_LEN];
System.arraycopy(salt, 0, encrKey, encrKeyOffset, salt.length);
encrKeyOffset += salt.length;
System.arraycopy(tmpKey, 0, encrKey, encrKeyOffset, tmpKey.length);
encrKeyOffset += tmpKey.length;
// Append digest(password, plainKey) as an integrity check to "encrKey"
md.update(passwdBytes);
Arrays.fill(passwdBytes, (byte) 0x00);
passwdBytes = null;
md.update(plainKey);
digest = md.digest();
md.reset();
System.arraycopy(digest, 0, encrKey, encrKeyOffset, digest.length);
// wrap the protected private key in a PKCS#8-style
// EncryptedPrivateKeyInfo, and returns its encoding
AlgorithmId encrAlg;
try {
encrAlg = new AlgorithmId(new ObjectIdentifier(KEY_PROTECTOR_OID));
return new EncryptedPrivateKeyInfo(encrAlg, encrKey).getEncoded();
} catch (IOException ioe) {
throw new KeyStoreException(ioe.getMessage());
}
}
use of sun.security.x509.AlgorithmId in project jdk8u_jdk by JetBrains.
the class RSASignature method decodeSignature.
/**
* Decode the signature data. Verify that the object identifier matches
* and return the message digest.
*/
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] sig) throws IOException {
// Enforce strict DER checking for signatures
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
DerValue[] values = in.getSequence(2);
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("SEQUENCE length error");
}
AlgorithmId algId = AlgorithmId.parse(values[0]);
if (algId.getOID().equals((Object) oid) == false) {
throw new IOException("ObjectIdentifier mismatch: " + algId.getOID());
}
if (algId.getEncodedParams() != null) {
throw new IOException("Unexpected AlgorithmId parameters");
}
byte[] digest = values[1].getOctetString();
return digest;
}
Aggregations