use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project cas by apereo.
the class WsFederationHelper method getEncryptionCredential.
/**
* Gets encryption credential.
* The encryption private key will need to contain the private keypair in PEM format.
* The encryption certificate is shared with ADFS in DER format, i.e certificate.crt.
*
* @param config the config
* @return the encryption credential
*/
@SneakyThrows
private static Credential getEncryptionCredential(final WsFederationConfiguration config) {
LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey());
val br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8));
Security.addProvider(new BouncyCastleProvider());
LOGGER.debug("Parsing credential private key");
try (val pemParser = new PEMParser(br)) {
val privateKeyPemObject = pemParser.readObject();
val converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());
val kp = FunctionUtils.doIf(Predicates.instanceOf(PEMEncryptedKeyPair.class), Unchecked.supplier(() -> {
LOGGER.debug("Encryption private key is an encrypted keypair");
val ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
val decProv = new JcePEMDecryptorProviderBuilder().build(config.getEncryptionPrivateKeyPassword().toCharArray());
LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password");
return converter.getKeyPair(ckp.decryptKeyPair(decProv));
}), Unchecked.supplier(() -> {
LOGGER.debug("Extracting a keypair from the private key");
return converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
})).apply(privateKeyPemObject);
val certParser = new X509CertParser();
LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate());
certParser.engineInit(config.getEncryptionCertificate().getInputStream());
LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate());
val cert = (X509CertificateObject) certParser.engineRead();
LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN());
return new BasicX509Credential(cert, kp.getPrivate());
}
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project leopard by tanhaichao.
the class tls_sigature method CheckTLSSignatureEx.
public static CheckTLSSignatureResult CheckTLSSignatureEx(String urlSig, long sdkAppid, String identifier, String publicKey) throws DataFormatException {
CheckTLSSignatureResult result = new CheckTLSSignatureResult();
Security.addProvider(new BouncyCastleProvider());
// DeBaseUrl64 urlSig to json
Base64 decoder = new Base64();
byte[] compressBytes = base64_url.base64DecodeUrl(urlSig.getBytes(Charset.forName("UTF-8")));
// Decompression
Inflater decompression = new Inflater();
decompression.setInput(compressBytes, 0, compressBytes.length);
byte[] decompressBytes = new byte[1024];
int decompressLength = decompression.inflate(decompressBytes);
decompression.end();
String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
// Get TLS.Sig from json
JSONObject jsonObject = new JSONObject(jsonString);
String sigTLS = jsonObject.getString("TLS.sig");
// debase64 TLS.Sig to get serailString
byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
try {
String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
String sigTime = jsonObject.getString("TLS.time");
String sigExpire = jsonObject.getString("TLS.expire_after");
if (Integer.parseInt(strSdkAppid) != sdkAppid) {
result.errMessage = new String("sdkappid " + strSdkAppid + " in tls sig not equal sdkappid " + sdkAppid + " in request");
return result;
}
if (System.currentTimeMillis() / 1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
result.errMessage = new String("TLS sig is out of date");
return result;
}
// Get Serial String from json
String SerialString = "TLS.appid_at_3rd:" + 0 + "\n" + "TLS.account_type:" + 0 + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + sdkAppid + "\n" + "TLS.time:" + sigTime + "\n" + "TLS.expire_after:" + sigExpire + "\n";
Reader reader = new CharArrayReader(publicKey.toCharArray());
PEMParser parser = new PEMParser(reader);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
Object obj = parser.readObject();
parser.close();
PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj);
Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
signature.initVerify(pubKeyStruct);
signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
boolean bool = signature.verify(signatureBytes);
result.expireTime = Integer.parseInt(sigExpire);
result.initTime = Integer.parseInt(sigTime);
result.verifyResult = bool;
} catch (Exception e) {
e.printStackTrace();
result.errMessage = "Failed in checking sig";
}
return result;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project leopard by tanhaichao.
the class tls_sigature method GenTLSSignatureEx.
/**
* @brief 生成 tls 票据,精简参数列表
* @param skdAppid 应用的 sdkappid
* @param identifier 用户 id
* @param privStr 私钥文件内容
* @param expire 有效期,以秒为单位,推荐时长一个月
* @return
* @throws IOException
*/
public static GenTLSSignatureResult GenTLSSignatureEx(long skdAppid, String identifier, String privStr, long expire) throws IOException {
GenTLSSignatureResult result = new GenTLSSignatureResult();
Security.addProvider(new BouncyCastleProvider());
Reader reader = new CharArrayReader(privStr.toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PEMParser parser = new PEMParser(reader);
Object obj = parser.readObject();
parser.close();
PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);
String jsonString = "{" + "\"TLS.account_type\":\"" + 0 + "\"," + "\"TLS.identifier\":\"" + identifier + "\"," + "\"TLS.appid_at_3rd\":\"" + 0 + "\"," + "\"TLS.sdk_appid\":\"" + skdAppid + "\"," + "\"TLS.expire_after\":\"" + expire + "\"," + "\"TLS.version\": \"201512300000\"" + "}";
String time = String.valueOf(System.currentTimeMillis() / 1000);
String SerialString = "TLS.appid_at_3rd:" + 0 + "\n" + "TLS.account_type:" + 0 + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + skdAppid + "\n" + "TLS.time:" + time + "\n" + "TLS.expire_after:" + expire + "\n";
try {
// Create Signature by SerialString
Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
signature.initSign(privKeyStruct);
signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
byte[] signatureBytes = signature.sign();
String sigTLS = Base64.encodeBase64String(signatureBytes);
// Add TlsSig to jsonString
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.put("TLS.sig", (Object) sigTLS);
jsonObject.put("TLS.time", (Object) time);
jsonString = jsonObject.toString();
// compression
Deflater compresser = new Deflater();
compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));
compresser.finish();
byte[] compressBytes = new byte[512];
int compressBytesLength = compresser.deflate(compressBytes);
compresser.end();
String userSig = new String(base64_url.base64EncodeUrl(Arrays.copyOfRange(compressBytes, 0, compressBytesLength)));
result.urlSig = userSig;
} catch (Exception e) {
e.printStackTrace();
result.errMessage = "generate usersig failed";
}
return result;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project leopard by tanhaichao.
the class tls_sigature method GenTLSSignature.
/**
* @brief 生成 tls 票据
* @param expire 有效期,单位是秒,推荐一个月
* @param strAppid3rd 填写与 sdkAppid 一致字符串形式的值
* @param skdAppid 应用的 appid
* @param identifier 用户 id
* @param accountType 创建应用后在配置页面上展示的 acctype
* @param privStr 生成 tls 票据使用的私钥内容
* @return 如果出错,GenTLSSignatureResult 中的 urlSig为空,errMsg 为出错信息,成功返回有效的票据
* @throws IOException
*/
@Deprecated
public static GenTLSSignatureResult GenTLSSignature(long expire, String strAppid3rd, long skdAppid, String identifier, long accountType, String privStr) throws IOException {
GenTLSSignatureResult result = new GenTLSSignatureResult();
Security.addProvider(new BouncyCastleProvider());
Reader reader = new CharArrayReader(privStr.toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PEMParser parser = new PEMParser(reader);
Object obj = parser.readObject();
parser.close();
PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);
// Create Json string and serialization String
String jsonString = "{" + "\"TLS.account_type\":\"" + accountType + "\"," + "\"TLS.identifier\":\"" + identifier + "\"," + "\"TLS.appid_at_3rd\":\"" + strAppid3rd + "\"," + "\"TLS.sdk_appid\":\"" + skdAppid + "\"," + "\"TLS.expire_after\":\"" + expire + "\"" + "}";
// System.out.println("#jsonString : \n" + jsonString);
String time = String.valueOf(System.currentTimeMillis() / 1000);
String SerialString = "TLS.appid_at_3rd:" + strAppid3rd + "\n" + "TLS.account_type:" + accountType + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + skdAppid + "\n" + "TLS.time:" + time + "\n" + "TLS.expire_after:" + expire + "\n";
try {
// Create Signature by SerialString
Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
signature.initSign(privKeyStruct);
signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
byte[] signatureBytes = signature.sign();
String sigTLS = Base64.encodeBase64String(signatureBytes);
// System.out.println("#sigTLS : " + sigTLS);
// Add TlsSig to jsonString
JSONObject jsonObject = new JSONObject(jsonString);
jsonObject.put("TLS.sig", (Object) sigTLS);
jsonObject.put("TLS.time", (Object) time);
jsonString = jsonObject.toString();
// System.out.println("#jsonString : \n" + jsonString);
// compression
Deflater compresser = new Deflater();
compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));
compresser.finish();
byte[] compressBytes = new byte[512];
int compressBytesLength = compresser.deflate(compressBytes);
compresser.end();
// System.out.println("#compressBytes "+ compressBytesLength+": " + Hex.encodeHexString(Arrays.copyOfRange(compressBytes,0,compressBytesLength)));
// String userSig = Base64.encodeBase64URLSafeString(Arrays.copyOfRange(compressBytes,0,compressBytesLength));
String userSig = new String(base64_url.base64EncodeUrl(Arrays.copyOfRange(compressBytes, 0, compressBytesLength)));
result.urlSig = userSig;
// System.out.println("urlSig: "+ userSig);
} catch (Exception e) {
e.printStackTrace();
result.errMessage = "generate usersig failed";
}
return result;
}
use of org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter in project meecrowave by apache.
the class LetsEncryptReloadLifecycle method loadOrCreateKeyPair.
private KeyPair loadOrCreateKeyPair(final int keySize, final File file) {
if (file.exists()) {
try (final PEMParser parser = new PEMParser(new FileReader(file))) {
return new JcaPEMKeyConverter().getKeyPair(PEMKeyPair.class.cast(parser.readObject()));
} catch (final IOException ex) {
throw new IllegalStateException("Can't read PEM file: " + file, ex);
}
} else {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keySize);
final KeyPair keyPair = keyGen.generateKeyPair();
try (final JcaPEMWriter writer = new JcaPEMWriter(new FileWriter(file))) {
writer.writeObject(keyPair);
} catch (final IOException ex) {
throw new IllegalStateException("Can't read PEM file: " + file, ex);
}
return keyPair;
} catch (final NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
}
}
Aggregations