HttpURLConnection 请求头里面设置时间戳
时间: 2023-10-12 13:15:54 浏览: 316
在 Java 中使用 HttpURLConnection 发送 HTTP 请求,可以在请求头中设置时间戳。具体操作如下:
1. 获取当前时间的时间戳(以毫秒为单位):
```
long timestamp = System.currentTimeMillis();
```
2. 在 HttpURLConnection 对象中设置请求头,将时间戳添加到请求头中:
```
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("timestamp", String.valueOf(timestamp));
```
其中,"timestamp" 是请求头的键,String.valueOf(timestamp) 是请求头的值,即当前时间的时间戳。
在服务端接收到请求后,可以从请求头中获取时间戳,判断请求是否过期或被篡改。
相关问题
在 Java 中使用 HttpURLConnection 发送 HTTP 请求, header里面添加签名和盐值
在 Java 中使用 HttpURLConnection 发送 HTTP 请求,可以在请求头中添加签名和盐值,以增强请求的安全性。具体操作如下:
1. 获取当前时间的时间戳(以毫秒为单位):
```
long timestamp = System.currentTimeMillis();
```
2. 获取需要加密的参数,拼接成一个字符串:
```
String params = "param1=value1¶m2=value2×tamp=" + timestamp + "&salt=" + salt;
```
其中,param1、param2 是需要发送的参数,value1、value2 是参数的值,timestamp 是当前时间的时间戳,salt 是盐值。
3. 对参数进行签名,生成签名字符串:
```
String sign = encrypt(params, secretKey);
```
其中,encrypt 是签名算法,secretKey 是用于签名的密钥。
4. 在 HttpURLConnection 对象中设置请求头,将签名和盐值添加到请求头中:
```
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("salt", salt);
connection.setRequestProperty("sign", sign);
```
其中,"salt" 是请求头的键,salt 是盐值,"sign" 是请求头的键,sign 是签名字符串。
在服务端接收到请求后,可以从请求头中获取盐值和签名,验证请求是否合法。
Java实现可信时间戳
可信时间戳是指一种数字签名技术,可以证明某个数字签名是在特定的时间之前完成的。Java中可以使用Bouncy Castle库来实现可信时间戳功能。
以下是一个简单的Java代码示例,用于生成和验证可信时间戳:
```java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.cms.TimeStampToken;
import org.bouncycastle.asn1.tsp.MessageImprint;
import org.bouncycastle.asn1.tsp.TSTInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.SignerInfoGenerator;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationGenerator;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder;
import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.bc.BcDigestCalculatorProvider;
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
import org.bouncycastle.tsp.TSPException;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampTokenGenerator;
public class TrustedTimestamp {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
// 输入要签名的数据
byte[] data = "Hello World".getBytes();
// 创建时间戳请求
TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();
reqGen.setCertReq(true);
byte[] digest = getMessageDigest(data);
TimeStampRequest req = reqGen.generate(
new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), digest);
// 发送时间戳请求并接收响应
byte[] tsTokenBytes = getTimestampToken(req.getEncoded());
// 解析时间戳响应并验证签名
TimeStampToken tsToken = new TimeStampToken(new ContentInfo(
SignedData.getInstance(tsTokenBytes)));
if (tsToken.isSignatureValid(new SignerInformationStore(
tsToken.getSignedContent()
.getContentInfo()
.getContentType(),
tsToken.getSignedContent()
.getContentInfo()
.getContent()))) {
System.out.println("Timestamp signature verified.");
} else {
System.out.println("Timestamp signature verification failed!");
}
// 验证时间戳中的原文摘要值与输入数据的摘要值是否一致
TSTInfo tstInfo = tsToken.getTimeStampInfo().toTSTInfo();
if (MessageDigest.isEqual(digest, tstInfo.getMessageImprint()
.getHashedMessage())) {
System.out.println("Message digest verified.");
} else {
System.out.println("Message digest verification failed!");
}
}
private static byte[] getMessageDigest(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(data);
}
private static byte[] getTimestampToken(byte[] request) throws IOException,
OperatorCreationException, CertificateEncodingException, TSPException {
// 时间戳服务URL
String url = "http://timestamp.comodoca.com/authenticode";
// 时间戳服务用户名
String username = "username";
// 时间戳服务密码
String password = "password";
// 创建时间戳请求对象
Hashtable<String, String> headers = new Hashtable<>();
headers.put("Content-Type", "application/timestamp-query");
headers.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes()));
HttpTimestamper timestamper = new HttpTimestamper(url, headers);
// 获取时间戳响应数据
TimeStampResponse response = timestamper.generateTimeStampResponse(request);
// 提取时间戳令牌
TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
new JcaSignerInfoGeneratorBuilder(
new BcDigestCalculatorProvider())
.build(new BcRSAContentSignerBuilder(
response.getTimeStampToken().getSignedData()
.getDigestAlgorithm(),
response.getTimeStampToken().getSignedData()
.getEncapContentInfo()
.getContentEncryptionAlgorithm())
.build(response.getTimeStampToken()
.getSignerInfos()
.getSigners()
.iterator()
.next()
.getPrivateKey())));
tsTokenGen.setAccuracySeconds(1);
tsTokenGen.setAccuracyMillis(0);
tsTokenGen.setAccuracyMicros(0);
tsTokenGen.setTSA(new X509Certificate[]{response.getTimeStampToken()
.getCertificates()[0]});
return tsTokenGen.generate(new CMSProcessableByteArray(request),
false).getEncoded();
}
private static class HttpTimestamper {
private final String url;
private final Hashtable<String, String> headers;
HttpTimestamper(String url, Hashtable<String, String> headers) {
this.url = url;
this.headers = headers;
}
TimeStampResponse generateTimeStampResponse(byte[] request)
throws IOException, TSPException {
byte[] response = post(url, request, headers);
return new TimeStampResponse(response);
}
private static byte[] post(String url, byte[] data,
Hashtable<String, String> headers) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type",
headers.get("Content-Type"));
for (String key : headers.keySet()) {
if (!key.equalsIgnoreCase("Content-Type")) {
conn.setRequestProperty(key, headers.get(key));
}
}
OutputStream out = conn.getOutputStream();
out.write(data);
out.close();
InputStream in = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
in.close();
return baos.toByteArray();
}
}
}
```
代码中通过Bouncy Castle库实现了时间戳的生成和验证。在生成时间戳的过程中,需要调用时间戳服务的API来获取时间戳响应数据,并将响应数据转换为时间戳令牌;在验证时间戳的过程中,需要校验时间戳令牌的签名和原文摘要值。
注意,为了使用Bouncy Castle库,需要在代码中添加以下语句:
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
Security.addProvider(new BouncyCastleProvider());
```
同时,为了使用时间戳服务,需要替换代码中的时间戳服务URL、用户名和密码。
阅读全文
相关推荐












